From 3c35613efae19dbab8c257b66c7c105dacedd694 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 21:56:55 -0300 Subject: [PATCH 01/25] crypto: PEM decodes through codecs' over in place, the two-step decode_pem removed; an input past a pair's bound is input_too_long on every path --- doc/generated/messages.adoc | 6 +- doc/tables/crypto.json | 2 +- example/key_formats.cpp | 10 +- example/key_formats.expected | 2 +- .../crypto/curves/secp256k1/formats.hpp | 38 ++- include/webcpp/crypto/formats.hpp | 307 ++---------------- test/Jamfile | 48 +-- test/formats_ed25519_sodium_test.cpp | 59 +++- test/formats_pem_test.cpp | 264 +++++++++------ test/formats_verbs_test.cpp | 59 +++- test/formats_x25519_sodium_test.cpp | 55 +++- test/fuzz/Jamfile | 5 +- test/fuzz/ed25519_pem_pkcs8_fuzz.cpp | 9 +- test/fuzz/p256_pem_pkcs8_fuzz.cpp | 7 +- test/fuzz/secp256k1_pem_pkcs8_fuzz.cpp | 9 +- test/fuzz/target.hpp | 124 +++++-- test/fuzz/x25519_pem_pkcs8_fuzz.cpp | 7 +- .../pem_decode_from_bytes.cpp | 8 +- test/p256_formats_bearssl_test.cpp | 107 ++++-- test/p256_wycheproof_bearssl_test.cpp | 33 +- test/secp256k1_der_test.cpp | 25 +- test/secp256k1_formats_test.cpp | 177 ++++++++-- test/secp256k1_keys_test.cpp | 22 +- test/support/ec_formats.hpp | 54 ++- test/support/format_checks.hpp | 108 +++++- test/support/rfc8410_formats.hpp | 40 ++- 26 files changed, 972 insertions(+), 613 deletions(-) diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 7e7fde7c..26379108 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -595,9 +595,9 @@ The fix: Leave the backend out, as in `+curves::p256::keypair+`, or name `+backe |`+pem_decode_from_bytes+` |native, wasip2, wasip3 -|`+webcpp::crypto: a PEM decodes from a text: a std::string_view, or a contiguous range of char+` +|`+static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char+` -The fix: Give a PEM to `+crypto::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. +The fix: Give a PEM to `+crypto::decode+` or `+codecs::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. |`+pem_header_removed+` |native, wasip2, wasip3 @@ -2184,7 +2184,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+pem_decode_from_bytes+` |the compile -|Give a PEM to `+crypto::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. +|Give a PEM to `+crypto::decode+` or `+codecs::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. |`+pem_header_removed+` |the compile diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 739be20d..50d5230d 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1455,7 +1455,7 @@ "format_without_header": "Include ``, or the curve's `/formats.hpp>`, which includes it: `crypto::formats` is declared by `config.hpp` and filled by the formats headers alone.", "decode_refusal_reason_toy": "Decode the x-only form into the type that holds it, as secp256k1's `curves::secp256k1::xonly_public_key`; the type this refuses has the form to encode only.", "refusal_reason_toy": "Encode the signature with `crypto::formats::raw`: an Ed25519 or BIP340 signature has no DER form, its 64 bytes are the signature.", - "pem_decode_from_bytes": "Give a PEM to `crypto::decode` as a text: a `std::string_view`, a `std::string`, or a contiguous range of `char` such as `std::span`; DER bytes decode with `crypto::formats::spki` or `crypto::formats::pkcs8` themselves.", + "pem_decode_from_bytes": "Give a PEM to `crypto::decode` or `codecs::decode` as a text: a `std::string_view`, a `std::string`, or a contiguous sized range of `char` such as `std::span`; DER bytes decode with `crypto::formats::spki` or `crypto::formats::pkcs8` themselves.", "forms_without_default": "List `crypto::formats::default_form_t` in each `detail::forms_of` specialization, with the other point forms the type accepts.", "der_on_ed25519": "Encode an Ed25519 signature with `crypto::formats::raw`, or its member `signature.encode(crypto::formats::raw)`: its 64 bytes are the signature, and it has no DER form.", "ed25519_formats_header_missing": "Include ``, which registers Ed25519's formats, beside ``.", diff --git a/example/key_formats.cpp b/example/key_formats.cpp index b00edcdc..59bcab4b 100644 --- a/example/key_formats.cpp +++ b/example/key_formats.cpp @@ -11,11 +11,11 @@ // carries the public key too. Prints the PEM texts and each verdict. // // tag::program[] +#include #include #include #include #include -#include #include #include @@ -24,6 +24,7 @@ #include #include +namespace codecs = webcpp::codecs; namespace crypto = webcpp::crypto; namespace formats = webcpp::crypto::formats; namespace ed25519 = webcpp::crypto::curves::ed25519; @@ -91,11 +92,12 @@ bool x25519_to_pem() { return true; } -// Version 2 is refused: strict decoding takes one form, and its PKCS#8 is longer than version 1's. +// Version 2 is refused: strict decoding takes one form, and its PKCS#8 is longer than version 1's, +// past the format's decode bound, so codecs refuses it before the value codec reads it. bool version2_refused() { auto const pair = crypto::decode(formats::pem(formats::pkcs8), version2_pem); - if (!pair && pair.error() == crypto::error::invalid_encoding) { - std::printf("version 2 refused: invalid_encoding\n"); + if (!pair && pair.error() == codecs::error::input_too_long) { + std::printf("version 2 refused: input_too_long\n"); return true; } return false; diff --git a/example/key_formats.expected b/example/key_formats.expected index 206a1ee8..82602a37 100644 --- a/example/key_formats.expected +++ b/example/key_formats.expected @@ -4,5 +4,5 @@ MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE= -----BEGIN PUBLIC KEY----- MCowBQYDK2VuAyEAhSDwCYkwp1R0i33ctD73Wg2/Og0mOBr066SpjqqbTmo= -----END PUBLIC KEY----- -version 2 refused: invalid_encoding +version 2 refused: input_too_long signed and verified diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp index f05b43c3..c7e47f7e 100644 --- a/include/webcpp/crypto/curves/secp256k1/formats.hpp +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -1243,6 +1243,12 @@ auto basic_keypair::decode(Format const& format, Input const& input) no * pair checked as `crypto::decode` checks it, then the detail decode the value codec runs with the * default resource (design R2), run with the caller's. * + * An input longer than the pair's decode bound, `formats::max_decode_input_size`, is + * `codecs::error::input_too_long`, as `codecs::decode` gives it, before the detail decode reads a + * byte. A PEM is decoded by codecs' typed decode of its armor, with the inner format's label, into + * a `codecs::secret_bytes` of the PKCS#8's decode bound (no heap, wiped when it goes, the armor's + * errors first, a payload past the bound `input_too_long`), then the detail decode of its DER. + * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. @@ -1260,21 +1266,37 @@ auto basic_keypair::decode(Format const& format, Input const& input, detail::refuse_pair(); return result_type{error::invalid_encoding}; } else if constexpr (std::is_same_v>) { - return detail::decode_pem_with( - format, input, [memory_resource](std::span der_bytes) { - return detail::secp256k1_keypair_of_pkcs8(der_bytes, memory_resource); - }); + constexpr std::size_t bound = + formats::max_decode_input_size; + auto const der_bytes = codecs::decode>( + detail::pem_armor_of(format), input); + if (!der_bytes) { + // A payload past the bound does not fit: the error over gives past the same bound. + if (der_bytes.error() == codecs::error::output_too_small) { + return result_type{codecs::error::input_too_long}; + } + return result_type{der_bytes.error()}; + } + // Read unchecked: the error was returned above. + return detail::secp256k1_keypair_of_pkcs8(der_bytes.unsafe_value().view(), + memory_resource); } else { static_assert(std::is_convertible_v>, "webcpp::crypto: a key pair decodes from bytes: a " "std::span, or what converts to one"); if constexpr (!std::is_convertible_v>) { return result_type{error::invalid_encoding}; - } else if constexpr (std::is_same_v) { - return detail::secp256k1_keypair_of_pkcs8(input, memory_resource); } else { - static_assert(std::is_same_v>); - return detail::secp256k1_keypair_of_raw(input, memory_resource); + std::span const input_bytes = input; + if (input_bytes.size() > formats::max_decode_input_size) { + return result_type{codecs::error::input_too_long}; + } + if constexpr (std::is_same_v) { + return detail::secp256k1_keypair_of_pkcs8(input_bytes, memory_resource); + } else { + static_assert(std::is_same_v>); + return detail::secp256k1_keypair_of_raw(input_bytes, memory_resource); + } } } } diff --git a/include/webcpp/crypto/formats.hpp b/include/webcpp/crypto/formats.hpp index 54913f7b..3da8fc47 100644 --- a/include/webcpp/crypto/formats.hpp +++ b/include/webcpp/crypto/formats.hpp @@ -14,8 +14,8 @@ (`detail::formats_of`, `detail::forms_of`, `detail::curve_of_v`, the refusal reasons); the two bounds of a value codec, `formats::max_encoded_size` and `formats::max_decode_input_size`; and the verbs `crypto::encode` and `crypto::decode`, which check a pair of crypto's against the type's - list and then call codecs' verbs, decoding a PEM in place; and the members `encode` and `decode` - of every signature type (`detail::basic_signature`), which call the verbs. + list and then call codecs' verbs, which decode a PEM in place; and the members `encode` and + `decode` of every signature type (`detail::basic_signature`), which call the verbs. Each pair of a format and a type is a `codecs::value_codec` specialization in the type's curve's `curves//formats.hpp`; this header includes no curve and no backend, and is the only one, @@ -36,14 +36,10 @@ #include #include #include -#include -#include #include -#include #include #include -#include #include #include #include @@ -341,10 +337,12 @@ inline constexpr std::size_t max_encoded_size = codecs::value_codec:: /** * The decode bound of the value codec of `Format` and `T`: the longest encoded input its decode - * accepts (owner decision 23, design R37). + * accepts (owner decision 23, design R37), the pair's acceptance contract. * - * It sizes the in-place decode of the pair's PEM, and equals @ref max_encoded_size for every pair - * of crypto's until a change rules otherwise. + * codecs refuses a longer input with `codecs::error::input_too_long` before the value codec reads + * a byte, directly and through PEM (codecs' owner decision 29); it sizes the in-place intermediate + * of the pair's PEM in codecs' `over`, and equals @ref max_encoded_size for every pair of crypto's + * until a change rules otherwise. * * @tparam Format The format's type. * @tparam T The value's type. @@ -682,17 +680,6 @@ consteval bool check_bounds() noexcept { return bytes.size(); } -/** - * Whether the value codec of `Format` and `Value` is secret: it states `secret`, and it is true. - * The member is optional in codecs' contract, and absent from a public value codec. - * - * @tparam Format The format's type. - * @tparam Value The value's type. - */ -template -inline constexpr bool value_codec_secret_v = - requires { requires static_cast(codecs::value_codec::secret); }; - /** * Whether crypto checks a call of `Format` on `Value`: `Value` is a type of crypto's and `Format` * a format of crypto's. Any other pair is codecs' to check. @@ -832,21 +819,6 @@ consteval bool encode_is_noexcept() { } } -/** - * The inner format of a PEM format, `type`; none for another format. - * - * @tparam Format The format's type. - */ -template -struct pem_inner {}; - -/** The inner link of a PEM. */ -template -struct pem_inner> { - /** The DER format inside the armor. */ - using type = Inner; -}; - /** * Whether a call of `Format` on `Value` runs with the inner format's fixed label (owner decision * 1, "the label can never be wrong"): `Format` is a PEM and the pair is crypto's. A hand-built @@ -885,80 +857,10 @@ template } /** - * Whether `Text` is a text a PEM decodes from, as codecs takes one: a type that converts to - * `std::string_view`, or a contiguous sized range of `char` (`std::span`, - * `std::vector`). - * - * @tparam Text The input's type. - */ -template -concept pem_text = - std::is_convertible_v || - (std::ranges::contiguous_range && std::ranges::sized_range && - std::is_same_v, char>); - -/** - * Whether the inner value codec of a PEM of `Value` states its decode bound, which sizes the - * in-place decode (owner decision 23). - * - * @tparam Inner The PEM's inner format. - * @tparam Value The value's type. - */ -template -inline constexpr bool states_decode_bound_v = - requires { codecs::value_codec::max_decode_input_size; }; - -/** - * Whether `crypto::decode(format, input)` decodes in place (design R24): `Format` is a PEM, - * and either the pair is crypto's, which never goes to codecs' heap path (`decode_pem` stops the - * build on an input that is no text or an inner pair without its decode bound), or `Input` is a - * text and the inner value codec decodes bytes into `Value` and states its decode bound. - * - * @tparam Value The value's type. - * @tparam Format The format's type. - * @tparam Input The input's type. - */ -template -inline constexpr bool decodes_in_place_v = false; - -/** A PEM of crypto's pair, or of a text whose inner value codec states its bound, is in place. */ -template -inline constexpr bool decodes_in_place_v, Input> = - checked_by_crypto_v, Value> || requires { - requires pem_text; - requires codecs::decodable; - requires codecs::value_codec::output == codecs::output_kind::bytes; - requires codecs::value_codec::max_decode_input_size > 0; - }; - -/** - * Whether the in-place decode of a PEM in `Format` into a `Value` cannot throw: the armor's step - * cannot, so it is as the inner value codec's decode of bytes, as codecs calls it; `noexcept` for - * every pair of crypto's but a key pair whose decode allocates from a memory resource (secp256k1's - * signing context). - * - * @tparam Value The value's type. - * @tparam Format The PEM format's type, `formats::pem_t`. - * @return Whether the decode is `noexcept`. - */ -template -consteval bool pem_decode_is_noexcept() { - using inner_type = pem_inner::type; - if constexpr (requires { - codecs::decode(std::declval(), - std::declval>()); - }) { - return noexcept(codecs::decode(std::declval(), - std::declval>())); - } else { - return true; - } -} - -/** - * Whether `crypto::decode` of `Input` in `Format` cannot throw: the in-place PEM decode is - * as its inner value codec's decode; any other is as codecs' verb, `noexcept` for every pair of - * crypto's but a key pair whose decode allocates from a memory resource. + * Whether `crypto::decode` of `Input` in `Format` cannot throw: codecs' verb's answer for a + * pair that passes crypto's check, a PEM of crypto's pair through the format with its inner + * format's label (the same type); `noexcept` for every pair of crypto's but a key pair whose decode + * allocates from a memory resource (secp256k1's signing context). * * @tparam Value The value's type. * @tparam Format The format's type. @@ -967,169 +869,14 @@ consteval bool pem_decode_is_noexcept() { */ template consteval bool decode_is_noexcept() { - if constexpr (!pair_accepted()) { - return true; - } else if constexpr (decodes_in_place_v) { - return pem_decode_is_noexcept(); - } else { + if constexpr (pair_accepted()) { return noexcept( codecs::decode(std::declval(), std::declval())); - } -} - -/** - * The text of `text` as a `std::string_view`: its conversion, or its characters. - * - * @tparam Text A `pem_text`. - * @param text The text. - * @return A view of its characters. - */ -template -[[nodiscard]] std::string_view pem_text_view(Text const& text) noexcept { - if constexpr (std::is_convertible_v) { - return text; } else { - return {std::ranges::data(text), std::ranges::size(text)}; - } -} - -/** - * The two steps of the in-place PEM decode into `der`: the armor through codecs' buffer form, then - * `inner_decode` over the bytes it wrote. A payload longer than `der` is crypto's - * `invalid_encoding`; every other error of either step is returned unchanged. - * - * @tparam Value The value's type. - * @tparam InnerDecode The inner step's type. - * @param armor The armor, `pem_armor_of`'s. - * @param text The PEM text. - * @param der The buffer of the inner format's decode bound. - * @param inner_decode The inner step: the value of the DER's bytes, or the error. - * @return The value, or the error. - */ -template -[[nodiscard]] codecs::result decode_pem_into( - codecs::formats::armor_t const& armor, std::string_view text, std::span der, - InnerDecode const& - inner_decode) noexcept(noexcept(inner_decode(std::span{}))) { - codecs::result const written = codecs::decode(armor, text, der); - if (!written) { - if (written.error() == codecs::error::output_too_small) { - return error::invalid_encoding; - } - return written.error(); - } - // Read unchecked: the error was returned above. - return inner_decode(std::span(der.first(written.unsafe_value()))); -} - -/** - * The stack buffer of the in-place PEM decode, wiped by `secure::erase_secret` when it goes, on - * every path, when the decode is secret. - * - * @tparam Size The inner format's decode bound. - * @tparam Secret Whether the decode is secret. - */ -template -struct pem_buffer { - /** The DER the armor writes. */ - std::array bytes{}; - - /** Zeroed bytes. */ - pem_buffer() = default; - /** Not copied: the bytes stay in one place, where they are wiped. */ - pem_buffer(pem_buffer const&) = delete; - /** Not copied. */ - pem_buffer& operator=(pem_buffer const&) = delete; - /** Not moved: the bytes stay in one place, where they are wiped. */ - pem_buffer(pem_buffer&&) = delete; - /** Not moved. */ - pem_buffer& operator=(pem_buffer&&) = delete; - - /** Wipes the bytes of a secret decode. */ - ~pem_buffer() { - if constexpr (Secret) { - secure::erase_secret(bytes); - } - } -}; - -/** - * Decodes the PEM `text` into a `Value` in place (design R24), the inner step `inner_decode`: the - * armor through codecs' buffer form into a stack buffer of the inner format's decode bound, - * `max_decode_input_size` (owner decision 23), then `inner_decode` over the DER, allocating - * nothing of its own. `decode_pem`'s inner step is the inner value codec, as codecs calls it; a - * secp256k1 key pair's decode with a memory resource gives its own, which takes the key pair's - * signing context from the caller's resource (design R2). - * - * `text` converts to a `std::string_view` or is a contiguous sized range of `char`, as codecs - * takes a text; any other input, and an inner pair that states no decode bound, stop the build. A - * payload longer than the buffer is crypto's `invalid_encoding`; the armor's errors are codecs', - * unchanged, and come first, as `codecs::decode` gives them. When the inner value codec is secret, - * or the value is (`codecs::is_secret_v`), the call holds `secure::timing_guard` and the buffer is - * wiped by `secure::erase_secret` on every path, an exception's (a key pair's memory resource) - * included. - * - * @tparam Value The value's type. - * @tparam Format The PEM format's type, `formats::pem_t`. - * @tparam Text The text's type. - * @tparam InnerDecode The inner step's type. - * @param format The PEM format. - * @param text The PEM text. - * @param inner_decode The inner step: the value of the DER's bytes, or the error. - * @return The value, or the error. - */ -template -[[nodiscard]] codecs::result -decode_pem_with(Format const& format, Text const& text, InnerDecode const& inner_decode) noexcept( - noexcept(inner_decode(std::span{}))) { - using inner_type = pem_inner::type; - constexpr bool secret = value_codec_secret_v || codecs::is_secret_v; - secure::timing_guard const timing_scope{secret}; - static_assert(pem_text, - "webcpp::crypto: a PEM decodes from a text: a std::string_view, or a contiguous " - "range of char"); - if constexpr (pem_text) { - static_assert(states_decode_bound_v, - "webcpp::crypto: a value codec that decodes states max_decode_input_size, " - "its decode bound"); - if constexpr (states_decode_bound_v) { - pem_buffer, secret> der; - return decode_pem_into(pem_armor_of(format), pem_text_view(text), - std::span(der.bytes), inner_decode); - } else { - return error::invalid_encoding; - } - } else { - return error::invalid_encoding; + return true; } } -/** - * Decodes the PEM `text` into a `Value` in place (design R24): `decode_pem_with` whose inner step - * is the inner value codec, as `codecs::decode` calls it, holding `secure::timing_guard` - * when the decode is secret, as `decode_pem_with` does. - * - * @tparam Value The value's type. - * @tparam Format The PEM format's type, `formats::pem_t`. - * @tparam Text The text's type. - * @param format The PEM format. - * @param text The PEM text. - * @return The value, or the error. - */ -template -[[nodiscard]] codecs::result decode_pem(Format const& format, Text const& text) noexcept( - pem_decode_is_noexcept()) { - using inner_type = pem_inner::type; - // Its own guard first, as every function of crypto's that a secret decode enters. - constexpr bool secret = value_codec_secret_v || codecs::is_secret_v; - secure::timing_guard const timing_scope{secret}; - return decode_pem_with( - format, text, - // Generic, so that its body is instantiated only where the armor's step reaches it. - [&format](auto const der_bytes) noexcept(pem_decode_is_noexcept()) - -> codecs::result { return codecs::decode(format.inner, der_bytes); }); -} - } // namespace detail /** @@ -1172,19 +919,22 @@ template /** * Decodes `input` in `format` into a `Value`: checks the pair against crypto's list, as `encode` - * does, then decodes a PEM text in place (design R24), and anything else with - * `codecs::decode(format, input)` (design R18). + * does, then returns `codecs::decode(format, input)` (design R18), a PEM of crypto's pair + * with its inner format's label. * * `input` is a `std::span` (or any byte input) for a binary format and a * `std::string_view` (or any text) for a PEM, as the value codec's output kind says (design R4). - * The PEM's armor is codecs': lines ended by a line feed or a carriage return and a line feed, the - * last ending optional, nothing before BEGIN or after END; its errors are codecs'; a payload longer - * than the inner format's decode bound is `crypto::error::invalid_encoding`. A PEM of crypto's pair - * is always decoded in place, never on codecs' heap path, and read with its inner format's label, - * whatever armor a hand-built `formats::pem_t` holds: another label is codecs' - * `invalid_prefix`. `noexcept` on every pair of crypto's but a key pair whose decode allocates from - * a memory resource (secp256k1's signing context); a pair crypto does not check is as - * `codecs::decode` is, which allocates for a heap result. + * An input longer than the pair's decode bound, `formats::max_decode_input_size`, is codecs' + * `codecs::error::input_too_long`, before the value codec reads a byte, directly and through PEM + * (codecs' owner decision 29). A PEM is decoded by codecs' `over`, in place: its DER held in an + * intermediate of the inner format's decode bound, never on the heap, wiped after a private + * format; the armor's errors are codecs' and come first (lines ended by a line feed or a carriage + * return and a line feed, the last ending optional, nothing before BEGIN or after END). A PEM of + * crypto's pair is read with its inner format's label, whatever armor a hand-built + * `formats::pem_t` holds: another label is codecs' `invalid_prefix`. `noexcept` on every pair of + * crypto's but a key pair whose decode allocates from a memory resource (secp256k1's signing + * context); a pair crypto does not check is as `codecs::decode` is, which allocates for a + * heap result. * * @tparam Value The value's type. * @tparam Format The format's type. @@ -1199,8 +949,9 @@ template if constexpr (!detail::pair_accepted()) { detail::refuse_pair(); return error::invalid_encoding; - } else if constexpr (detail::decodes_in_place_v) { - return detail::decode_pem(format, input); + } else if constexpr (detail::fixes_pem_label_v) { + return codecs::decode(Format{detail::pem_armor_of(format), format.inner}, + input); } else { return codecs::decode(format, input); } diff --git a/test/Jamfile b/test/Jamfile index 36c7bebc..d2a724da 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -223,17 +223,18 @@ crypto-run signing_namespaces : signing_namespaces_test.cpp crypto-run formats_vocabulary : formats_vocabulary_test.cpp ; # The verbs over the tests' toy type (support/formats_toy.hpp): every form # gives one encoding, nothing on the heap, strict decoding, secret results -# wiped when moved from, the two bounds and check_bounds, a moved-from key -# pair refused, a type crypto does not own passed to codecs untouched; the -# wipes through secure's seam (support/wipe_record.hpp). +# wiped when moved from, the two bounds and check_bounds, each pair's largest +# valid input decoded and one byte more input_too_long on every path, a +# moved-from key pair refused, a type crypto does not own passed to codecs +# untouched; the wipes through secure's seam (support/wipe_record.hpp). crypto-run formats_verbs : formats_verbs_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; -# The in-place PEM decode over the toy (design R24): the text OpenSSL writes, -# its CRLF form and one without the final line feed, no heap where codecs' -# decode of a std::string_view has one, the armor's refusals, a payload past -# the decode bound (an RSA key's) invalid_encoding, the DER buffer wiped after -# a pkcs8, the guard held for a private format alone, the same values and -# errors as codecs::decode. +# PEM over the toy through codecs' over, in place: the text OpenSSL writes, +# its CRLF form and one without the final line feed, no heap through +# crypto::decode, codecs::decode or the member, the armor's refusals, a payload +# past the decode bound (an RSA key's) input_too_long as its DER is, codecs' +# intermediate wiped after a pkcs8 and none made past the bound, codecs' guard +# held for a private format alone, the same values and errors on every path. crypto-run formats_pem : formats_pem_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The room for JWK (design R17): a stand-in text format of the tests' own, @@ -457,7 +458,8 @@ crypto-run secp256k1_wycheproof : secp256k1_wycheproof_test.cpp crypto-run secp256k1_ecdh : secp256k1_ecdh_test.cpp : /third_party//secp256k1 /third_party//wycheproof /webcpp//boost_json ; -# The parsed public key in both SEC1 forms, and its refusals. +# The parsed public key in both SEC1 forms, and its refusals (input_too_long +# past raw's decode bound). crypto-run secp256k1_keys : secp256k1_keys_test.cpp : /third_party//secp256k1 ; # Recoverable ECDSA signatures, libsecp256k1's edge cases, and hedged ECDSA. crypto-run secp256k1_recovery : secp256k1_recovery_test.cpp : /third_party//secp256k1 ; @@ -479,9 +481,11 @@ crypto-run secp256k1_tweak : secp256k1_tweak_test.cpp : /third_party//s # uncompressed by default, decoding a stored compressed one; the x-only key's # raw; the key pair's raw and pkcs8; the signatures' raw and the ECDSA one's # DER), the generator's key, 64 seeded key pairs, a Nostr key, the strict -# decoders' refusals, Wycheproof's ECDH SPKIs and ECDSA keys, PEM through -# codecs' armor; the key pair's decode with a memory resource into an arena; -# a throwing resource's unwinding through pem(pkcs8), its buffers wiped. +# decoders' refusals, input_too_long past each pair's bound and its largest +# valid input decoded, Wycheproof's ECDH SPKIs and ECDSA keys, PEM through +# codecs' armor; the key pair's decode with a memory resource into an arena, +# its refusals at the bounds as codecs::decode's; a throwing resource's +# unwinding through pem(pkcs8), its buffers wiped. crypto-run secp256k1_formats : secp256k1_formats_test.cpp : /third_party//secp256k1 /third_party//wycheproof /webcpp//boost_json WEBCPP_SECURE_TEST_WIPE_RECORD ; @@ -653,7 +657,8 @@ crypto-run p256_keys_bearssl : p256_keys_bearssl_test.cpp # and its refusals, low S checked and normalized, DER both ways and its strict # decoder. crypto-run p256_ecdsa_bearssl : p256_ecdsa_bearssl_test.cpp : /third_party//bearssl ; -# Wycheproof's P-256 SHA-256 ECDSA vectors, raw (IEEE P1363) and DER. +# Wycheproof's P-256 SHA-256 ECDSA vectors, raw (IEEE P1363) and DER (a DER +# past 72 bytes input_too_long). crypto-run p256_wycheproof_bearssl : p256_wycheproof_bearssl_test.cpp : /third_party//bearssl /third_party//wycheproof /webcpp//boost_json ; @@ -662,10 +667,11 @@ crypto-run p256_wycheproof_bearssl : p256_wycheproof_bearssl_test.cpp crypto-run p256_ecdh_bearssl : p256_ecdh_bearssl_test.cpp : /third_party//bearssl /third_party//wycheproof /webcpp//boost_json ; -# P-256's formats on BearSSL: every pair of design D4 in every form, the -# compressed point's square root, BearSSL's own PKCS#8 encoder as an oracle of -# the layout, the strict decoders' refusals, Wycheproof's compressed points, -# ECDH SPKIs and PEMs and ECDSA DER, PEM through codecs' armor. +# P-256's formats on BearSSL: every pair of design D4 in every form, each +# pair's largest valid input and one byte more input_too_long, the compressed +# point's square root, BearSSL's own PKCS#8 encoder as an oracle of the layout, +# the strict decoders' refusals, Wycheproof's compressed points, ECDH SPKIs and +# PEMs and ECDSA DER, PEM through codecs' armor, an RSA key's input_too_long. crypto-run p256_formats_bearssl : p256_formats_bearssl_test.cpp : /third_party//bearssl /third_party//wycheproof /webcpp//boost_json WEBCPP_SECURE_TEST_WIPE_RECORD ; @@ -784,11 +790,13 @@ crypto-run oracle_25519_corrupted : oracle_25519_test.cpp # RFC 8410's SPKI and PKCS#8 for Ed25519 and X25519, and PEM, on libsodium # (design D30): RFC 8410's own keys, round trips of random keys, every -# malformed input refused with invalid_encoding and nothing written. OpenSSL's +# malformed input refused with invalid_encoding, or input_too_long past the +# pair's decode bound, and nothing written. OpenSSL's # i2d_PUBKEY, i2d_PrivateKey and PEM writers as an outside oracle on native, # wasip2 and wasip3 (linked in the test alone), and node's WebCrypto importKey # and exportKey on Emscripten (the JSPI link, for EM_ASYNC_JS): 200 seeded -# cases per curve each. +# cases per curve each. An input past a pair's decode bound is input_too_long, +# each pair's largest valid input decodes. crypto-run formats_ed25519_sodium : formats_ed25519_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json WEBCPP_SECURE_TEST_WIPE_RECORD ; diff --git a/test/formats_ed25519_sodium_test.cpp b/test/formats_ed25519_sodium_test.cpp index ec0dd734..ebe66ffc 100644 --- a/test/formats_ed25519_sodium_test.cpp +++ b/test/formats_ed25519_sodium_test.cpp @@ -12,11 +12,15 @@ // pair's raw, its secret() and from_secret; Wycheproof's EdDSA public keys through raw, spki and // pem(spki); round trips of random key pairs; a PEM with CRLF lines and without its final line // feed decoded, and one with text before BEGIN refused (Review Focus 1); a moved-from key pair -// refused by every private format with nothing written (Review Focus 3); and every malformed DER -// refused with invalid_encoding: the other curve's OID, a trailing byte, a length in long form, -// PKCS#8 version 2 with the public key (30 51, 83 bytes, and RFC 8410's with an attribute), each -// byte of a prefix changed. The armor's own faults are codecs' (formats_pem_test pins crypto's -// pem over it); X25519's formats are formats_x25519_sodium_test's. +// refused by every private format with nothing written (Review Focus 3); each pair's largest +// valid input, exactly its decode bound, decoded on every path and one byte more codecs' +// input_too_long (one-verb's R9); RFC 8410's private PEM through codecs::decode with no heap, its +// 48-byte intermediate wiped; and every malformed DER refused: the other curve's OID, a trailing +// byte, a length in long form, each byte of a prefix changed with invalid_encoding, PKCS#8 version +// 2 with the public key (30 51, 83 bytes, and RFC 8410's of 116 with an attribute), past the +// PKCS#8's decode bound, with codecs' input_too_long, directly and through PEM. The armor's own +// faults are codecs' (formats_pem_test pins crypto's pem over it); X25519's formats are +// formats_x25519_sodium_test's. #include #include @@ -129,14 +133,19 @@ void rfc8410_keys() { BOOST_TEST(pkcs8.has_value() && bytes_of(pkcs8->view()) == der_of("PRIVATE KEY", rfc8410_private)); - // Section 10.3's version 2, with an attribute and the public key: 114 bytes of DER, past - // the decode bound in PEM, and refused as DER. + // Section 10.3's version 2, with an attribute and the public key: 116 bytes of DER, past + // the decode bound, codecs' input_too_long in PEM and as DER. auto const version2 = crypto::decode(formats::pem(formats::pkcs8), rfc8410_private_v2); - BOOST_TEST(!version2.has_value() && version2.error() == crypto::error::invalid_encoding); + BOOST_TEST(!version2.has_value() && version2.error() == codecs::error::input_too_long); + auto const version2_codecs = + codecs::decode(formats::pem(formats::pkcs8), rfc8410_private_v2); + BOOST_TEST(!version2_codecs.has_value() && + version2_codecs.error() == codecs::error::input_too_long); + auto const version2_der = der_of("PRIVATE KEY", rfc8410_private_v2); + BOOST_TEST_EQ(version2_der.size(), 116U); crypto::test::check_refused( - formats::pkcs8, der_of("PRIVATE KEY", rfc8410_private_v2), crypto::error::invalid_encoding, - "RFC 8410's version 2"); + formats::pkcs8, version2_der, codecs::error::input_too_long, "RFC 8410's version 2"); } /** @@ -229,6 +238,10 @@ static_assert(noexcept(std::declval().encode(formats::pem(format static_assert(noexcept(keypair::decode(formats::pkcs8, std::declval()))); static_assert(noexcept(std::declval().encode(formats::raw))); static_assert(noexcept(signature::decode(formats::raw, std::declval()))); +// codecs' decode of each PEM pair is noexcept (one-verb's R10). +static_assert(noexcept(codecs::decode(formats::pem(formats::spki), + std::string_view{}))); +static_assert(noexcept(codecs::decode(formats::pem(formats::pkcs8), std::string_view{}))); } // namespace member_checks /** @@ -275,6 +288,31 @@ void every_form() { crypto::test::check_secret_result(formats::pkcs8, *key_pair); crypto::test::check_secret_result(formats::pem(formats::pkcs8), *key_pair); crypto::test::check_secret_result(formats::raw, *key_pair); + + // The decode bound is each pair's acceptance contract (one-verb's R9). + crypto::test::check_largest_input, ed25519::public_key>(formats::raw, + public_key->bytes()); + crypto::test::check_largest_input, ed25519::public_key>(formats::spki, spki); + crypto::test::check_largest_input, ed25519::keypair>(formats::raw, seed); + crypto::test::check_largest_input(formats::pkcs8, pkcs8); + crypto::test::check_largest_input, ed25519::signature>(formats::raw, + signature->bytes()); +} + +/** + * RFC 8410's private PEM, as OpenSSL writes it, through codecs::decode: no heap, and codecs' + * intermediate, the PKCS#8's 48 bytes, wiped (secure's wipe record). + */ +void private_pem_through_codecs() { + webcpp::test::clear_wipes(); + std::size_t const before = webcpp::test::allocations(); + auto const decoded = + codecs::decode(formats::pem(formats::pkcs8), rfc8410_private); + std::size_t const after = webcpp::test::allocations(); + BOOST_TEST_EQ(after, before); + BOOST_TEST(decoded.has_value()); + std::vector const sizes = webcpp::test::wiped_sizes(); + BOOST_TEST_EQ(std::ranges::count(sizes, std::size_t{48}), 1); } /** A key pair's raw is its secret() and from_secret under the format's name (design R2). */ @@ -487,6 +525,7 @@ int main() { bounds(); refused_pairs(); every_form(); + private_pem_through_codecs(); key_pair_raw(); wycheproof_public_keys(); layouts(); diff --git a/test/formats_pem_test.cpp b/test/formats_pem_test.cpp index 69146a07..503ccd1b 100644 --- a/test/formats_pem_test.cpp +++ b/test/formats_pem_test.cpp @@ -4,16 +4,17 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// PEM over the tests' toy type (design R23, R24, owner decision 23, Review Focus 1 and 5): +// PEM over the tests' toy type (design D4, R7, R8, R9, owner decision 29, Review Focus 4): // crypto::encode(pem(spki), key) is codecs' armor of the SPKI, labelled from the inner format; -// crypto::decode reads it back in place, also with CRLF lines and without its final line feed, -// allocating nothing where codecs::decode of a std::string_view puts its intermediate on the heap -// (the documented difference); the armor's refusals are codecs' (a CERTIFICATE label, text before -// BEGIN); a payload past the inner format's decode bound, an RSA key's SPKI, and an armor of no -// bytes are invalid_encoding, nothing on the heap; the DER buffer is sized by the decode bound, so -// that pkcs8's 16-byte "version 2" decodes where a buffer of max_encoded_size would refuse it, and -// is wiped after a pkcs8, the guard held for a private format alone; every text gives the same -// value or the same error through crypto::decode and codecs::decode. +// crypto::decode, codecs::decode and the member read it back through codecs' over, in place, also +// with CRLF lines and without its final line feed, allocating nothing; the armor's refusals are +// codecs' (a CERTIFICATE label, text before BEGIN); a payload past the inner format's decode bound, +// an RSA key's SPKI, is codecs' input_too_long on every path, as the same DER given directly is, +// nothing on the heap; an armor of no bytes is the toy's invalid_encoding; pkcs8's 16-byte "version +// 2", its bound, decodes and 17 bytes are input_too_long; codecs' intermediate of a pkcs8 is wiped, +// the written bytes, under codecs' guard, and none is made past the bound; every text gives the +// same value or the same error through crypto::decode, codecs::decode and the member; codecs' +// decode of every PEM pair of the toy is noexcept. // The timing seam is defined before any webcpp header reads secure's guard. #include "support/timing_seam.hpp" @@ -29,6 +30,7 @@ #include #include +#include #include #include @@ -38,6 +40,7 @@ #include #include #include +#include #include namespace crypto = webcpp::crypto; @@ -77,6 +80,19 @@ constexpr std::string_view rsa_pem = "DwIDAQAB\n" "-----END PUBLIC KEY-----\n"; +// codecs' decode of every PEM pair of the toy is noexcept (design R10), as crypto's and the +// member's are, from every text. +static_assert(noexcept(codecs::decode(formats::pem(formats::spki), + std::declval()))); +static_assert(noexcept(codecs::decode(formats::pem(formats::spki), + std::declval const&>()))); +static_assert(noexcept(codecs::decode(formats::pem(formats::pkcs8), + std::declval()))); +static_assert(noexcept(crypto::decode(formats::pem(formats::pkcs8), + std::declval()))); +static_assert(noexcept(toy_keypair::decode(formats::pem(formats::pkcs8), + std::declval()))); + /** `text` with every line feed made a carriage return and a line feed. */ std::string with_crlf(std::string_view text) { std::string crlf; @@ -159,30 +175,38 @@ void decode_variants() { } /** - * The in-place decode allocates nothing; codecs::decode of the same std::string_view holds its - * intermediate on the heap (design R24, the guide's documented difference). + * Every decode of a PEM allocates nothing (design D4): crypto::decode, codecs::decode and the + * member, of both PEM pairs, from a std::string_view, a span of characters and a vector of them, + * the vector made before the count. */ void decode_in_place() { + auto const key_pair = toy_keypair::from_secret(secret_bytes); + auto const private_pem = crypto::encode(formats::pem(formats::pkcs8), key_pair); + if (!BOOST_TEST(private_pem.has_value())) { + return; + } + std::string_view const private_text = private_pem->view(); + std::vector const characters(key_pem.begin(), key_pem.end()); + std::span const span_text(key_pem.data(), key_pem.size()); std::size_t const before = webcpp::test::allocations(); auto const in_place = crypto::decode(formats::pem(formats::spki), key_pem); - std::size_t const after_in_place = webcpp::test::allocations(); auto const through_codecs = codecs::decode(formats::pem(formats::spki), key_pem); - std::size_t const after_codecs = webcpp::test::allocations(); - BOOST_TEST_EQ(after_in_place, before); - BOOST_TEST_GT(after_codecs, after_in_place); - BOOST_TEST(in_place.has_value()); - BOOST_TEST(through_codecs.has_value()); - - // Every text codecs takes decodes in place too, never on codecs' heap path: a span of - // characters and a vector of them, the vector made before the count. - std::vector const characters(key_pem.begin(), key_pem.end()); - std::span const span_text(key_pem.data(), key_pem.size()); - std::size_t const before_ranges = webcpp::test::allocations(); - auto const from_span = crypto::decode(formats::pem(formats::spki), span_text); - auto const from_vector = crypto::decode(formats::pem(formats::spki), characters); - std::size_t const after_ranges = webcpp::test::allocations(); - BOOST_TEST_EQ(after_ranges, before_ranges); - if (BOOST_TEST(from_span.has_value()) && BOOST_TEST(from_vector.has_value()) && in_place) { + auto const through_member = toy_key::decode(formats::pem(formats::spki), key_pem); + auto const private_in_place = + crypto::decode(formats::pem(formats::pkcs8), private_text); + auto const private_through_codecs = + codecs::decode(formats::pem(formats::pkcs8), private_text); + auto const from_span = codecs::decode(formats::pem(formats::spki), span_text); + auto const from_vector = codecs::decode(formats::pem(formats::spki), characters); + std::size_t const after = webcpp::test::allocations(); + BOOST_TEST_EQ(after, before); + BOOST_TEST(private_in_place.has_value()); + BOOST_TEST(private_through_codecs.has_value()); + if (BOOST_TEST(in_place.has_value()) && BOOST_TEST(through_codecs.has_value()) && + BOOST_TEST(through_member.has_value()) && BOOST_TEST(from_span.has_value()) && + BOOST_TEST(from_vector.has_value())) { + BOOST_TEST(*through_codecs == *in_place); + BOOST_TEST(*through_member == *in_place); BOOST_TEST(*from_span == *in_place); BOOST_TEST(*from_vector == *in_place); } @@ -204,30 +228,43 @@ void armor_refusals() { } /** - * A payload past the inner format's decode bound, an RSA key's SPKI of 294 bytes, and an armor of - * no bytes are invalid_encoding, with nothing on the heap (Review Focus 5); the payload of 294 - * bytes is written nowhere past the stack buffer (the fuzz lane's address sanitizer reads that). + * A payload past the inner format's decode bound, an RSA key's SPKI of 294 bytes, is codecs' + * input_too_long through crypto::decode, codecs::decode and the member, with nothing on the heap + * (Review Focus 4), as the same 294 bytes given directly to codecs::decode are; no intermediate is + * made for it, so nothing is written past the bound (the fuzz lane's address sanitizer reads + * that). An armor of no bytes reaches the toy's value codec: its invalid_encoding. */ void payload_past_the_bound() { std::size_t const before = webcpp::test::allocations(); auto const rsa = crypto::decode(formats::pem(formats::spki), rsa_pem); + auto const rsa_codecs = codecs::decode(formats::pem(formats::spki), rsa_pem); + auto const rsa_member = toy_key::decode(formats::pem(formats::spki), rsa_pem); std::size_t const after = webcpp::test::allocations(); BOOST_TEST_EQ(after, before); - BOOST_TEST(rsa.error() == crypto::error::invalid_encoding); + BOOST_TEST(rsa.error() == codecs::error::input_too_long); + BOOST_TEST(rsa_codecs.error() == codecs::error::input_too_long); + BOOST_TEST(rsa_member.error() == codecs::error::input_too_long); auto const rsa_der = codecs::decode(codecs::formats::armor("PUBLIC KEY"), rsa_pem); if (BOOST_TEST(rsa_der.has_value())) { BOOST_TEST_EQ(rsa_der->size(), 294U); + std::span const der(*rsa_der); + BOOST_TEST(codecs::decode(formats::spki, der).error() == + codecs::error::input_too_long); + BOOST_TEST(crypto::decode(formats::spki, der).error() == + codecs::error::input_too_long); } std::string const empty = armored("PUBLIC KEY", {}); BOOST_TEST_EQ(empty, std::string{"-----BEGIN PUBLIC KEY-----\n-----END PUBLIC KEY-----\n"}); BOOST_TEST(crypto::decode(formats::pem(formats::spki), empty).error() == crypto::error::invalid_encoding); + BOOST_TEST(codecs::decode(formats::pem(formats::spki), empty).error() == + crypto::error::invalid_encoding); } /** - * The DER buffer is sized by the inner format's decode bound (owner decision 23): the toy key - * pair's pkcs8 "version 2", 16 bytes, past its max_encoded_size of 12, decodes in place; 17 bytes - * are invalid_encoding. + * The decode bound is the pair's acceptance contract (design R9): the toy key pair's pkcs8 + * "version 2", 16 bytes, past its max_encoded_size of 12, decodes in place; 17 bytes are + * input_too_long through crypto::decode, codecs::decode and the member. */ void decode_bound_sizes_the_buffer() { static_assert(formats::max_encoded_size == 12); @@ -235,21 +272,30 @@ void decode_bound_sizes_the_buffer() { std::string const version_2 = armored("PRIVATE KEY", key_pair_pkcs8_v2); std::size_t const before = webcpp::test::allocations(); auto const decoded = crypto::decode(formats::pem(formats::pkcs8), version_2); + auto const through_codecs = + codecs::decode(formats::pem(formats::pkcs8), version_2); std::size_t const after = webcpp::test::allocations(); BOOST_TEST_EQ(after, before); - if (BOOST_TEST(decoded.has_value())) { + if (BOOST_TEST(decoded.has_value()) && BOOST_TEST(through_codecs.has_value())) { BOOST_TEST(std::ranges::equal(decoded->secret(), secret_bytes)); + BOOST_TEST(std::ranges::equal(through_codecs->secret(), secret_bytes)); } std::array longer{}; std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); - BOOST_TEST( - crypto::decode(formats::pem(formats::pkcs8), armored("PRIVATE KEY", longer)) - .error() == crypto::error::invalid_encoding); + std::string const too_long = armored("PRIVATE KEY", longer); + BOOST_TEST(crypto::decode(formats::pem(formats::pkcs8), too_long).error() == + codecs::error::input_too_long); + BOOST_TEST(codecs::decode(formats::pem(formats::pkcs8), too_long).error() == + codecs::error::input_too_long); + BOOST_TEST(toy_keypair::decode(formats::pem(formats::pkcs8), too_long).error() == + codecs::error::input_too_long); } /** - * The DER buffer of a pkcs8 is wiped, its whole decode bound, on success and on error; the one of a - * public decode is not. secure's wipe record sees every wipe leave only zero bytes. + * codecs' intermediate of a pkcs8, the DER the armor wrote (12 or 16 bytes, its payload's size), + * is wiped on success and on the value codec's refusal; past the bound, and on the armor's + * refusal, none is made, so the toy's decode reads no buffer; a public decode wipes none. secure's + * wipe record sees every wipe leave only zero bytes. */ void buffer_wiped() { auto const key_pair = toy_keypair::from_secret(secret_bytes); @@ -257,63 +303,50 @@ void buffer_wiped() { if (!BOOST_TEST(encoded.has_value())) { return; } - constexpr std::size_t buffer_size = - formats::max_decode_input_size; - // The buffer is found by its address, which the toy's pkcs8 decode records as its input. - webcpp::crypto::test::toy_pkcs8_decoded_from = nullptr; - webcpp::test::clear_wipes(); - { - auto const decoded = - crypto::decode(formats::pem(formats::pkcs8), encoded->view()); - BOOST_TEST(decoded.has_value()); - void const* const buffer = webcpp::crypto::test::toy_pkcs8_decoded_from; - BOOST_TEST(buffer != nullptr); - BOOST_TEST(webcpp::test::wiped(buffer, buffer_size)); + // The intermediate is found by its address, which the toy's pkcs8 decode records as its input. + auto const wiped_once = [](std::string_view text, std::size_t payload_size, bool valid) { + webcpp::crypto::test::toy_pkcs8_decoded_from = nullptr; + webcpp::test::clear_wipes(); + auto const decoded = codecs::decode(formats::pem(formats::pkcs8), text); + BOOST_TEST_EQ(decoded.has_value(), valid); + void const* const intermediate = webcpp::crypto::test::toy_pkcs8_decoded_from; + BOOST_TEST(intermediate != nullptr); + BOOST_TEST(webcpp::test::wiped(intermediate, payload_size)); std::vector const sizes = webcpp::test::wiped_sizes(); - BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); - } - webcpp::test::clear_wipes(); - { - std::string const corrupt = armored("PRIVATE KEY", std::span(key_pair_pkcs8_v2).first(15)); - auto const refused = crypto::decode(formats::pem(formats::pkcs8), corrupt); - BOOST_TEST(refused.error() == crypto::error::invalid_encoding); - BOOST_TEST(webcpp::test::wiped(webcpp::crypto::test::toy_pkcs8_decoded_from, buffer_size)); - std::vector const sizes = webcpp::test::wiped_sizes(); - BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); - } - { - // A payload past the decode bound (Review Focus 5 for a secret): the armor refuses to - // write it, so the toy's decode never sees the buffer and records no address; one wipe of - // the buffer's size is all the record shows (another call's address would not be this - // one's under other inlining or AddressSanitizer's fake stacks). - std::array longer{}; - std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); - auto const refused = crypto::decode(formats::pem(formats::pkcs8), - armored("PRIVATE KEY", longer)); - BOOST_TEST(refused.error() == crypto::error::invalid_encoding); - std::vector const sizes = webcpp::test::wiped_sizes(); - BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); - } - { - auto const refused = crypto::decode(formats::pem(formats::pkcs8), - armored("CERTIFICATE", key_spki)); - BOOST_TEST(refused.error() == codecs::error::invalid_prefix); - std::vector const sizes = webcpp::test::wiped_sizes(); - BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); - } - { - auto const decoded = crypto::decode(formats::pem(formats::spki), key_pem); - BOOST_TEST(decoded.has_value()); - // codecs' armor wipes its own state on every call; crypto wipes no buffer of a public key. + BOOST_TEST_EQ(std::ranges::count(sizes, payload_size), 1); + }; + wiped_once(encoded->view(), 12, true); + wiped_once(armored("PRIVATE KEY", key_pair_pkcs8_v2), 16, true); + wiped_once(armored("PRIVATE KEY", std::span(key_pair_pkcs8_v2).first(15)), 15, false); + + auto const no_intermediate = [](std::string_view text, boost::system::error_code expected) { + webcpp::crypto::test::toy_pkcs8_decoded_from = nullptr; + webcpp::test::clear_wipes(); + auto const refused = codecs::decode(formats::pem(formats::pkcs8), text); + BOOST_TEST(refused.error() == expected); + BOOST_TEST(webcpp::crypto::test::toy_pkcs8_decoded_from == nullptr); std::vector const sizes = webcpp::test::wiped_sizes(); - BOOST_TEST(std::ranges::count( - sizes, formats::max_decode_input_size, toy_key>) == 0); - } + for (std::size_t const payload_size : {12U, 16U, 17U}) { + BOOST_TEST_EQ(std::ranges::count(sizes, payload_size), 0); + } + }; + std::array longer{}; + std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); + no_intermediate(armored("PRIVATE KEY", longer), codecs::error::input_too_long); + no_intermediate(armored("CERTIFICATE", key_spki), codecs::error::invalid_prefix); + + webcpp::test::clear_wipes(); + auto const decoded = codecs::decode(formats::pem(formats::spki), key_pem); + BOOST_TEST(decoded.has_value()); + // codecs' armor wipes its own state on every call; no intermediate of a public key is wiped. + std::vector const sizes = webcpp::test::wiped_sizes(); + BOOST_TEST_EQ(std::ranges::count(sizes, key_spki.size()), 0); } /** - * The in-place decode of a private format holds crypto's guard, decode_pem's, first; a public one - * enters none of crypto's. + * The decode of a private format holds codecs' guard, the core's (design R12), first, refused or + * not; a public one enters no guard. The toy's value codecs are the tests', so crypto's own guards + * are not counted: the curves' formats tests read those. */ void guard_for_a_private_format() { auto const key_pair = toy_keypair::from_secret(secret_bytes); @@ -321,17 +354,32 @@ void guard_for_a_private_format() { if (!BOOST_TEST(encoded.has_value())) { return; } - webcpp::test::require_enters("detail::decode_pem of pem(pkcs8)", [&] { + auto const enters_a_guard = [](auto const& call) { + std::size_t const before = webcpp::test::timing_all_entries; + webcpp::test::timing_first_entry = nullptr; + call(); + bool const entered = webcpp::test::timing_all_entries != before && + webcpp::test::timing_first_entry != nullptr && + std::string_view{webcpp::test::timing_first_entry}.find( + "webcpp::codecs::") != std::string_view::npos; + webcpp::test::timing_first_entry = nullptr; + return entered; + }; + BOOST_TEST(enters_a_guard([&] { + BOOST_TEST( + codecs::decode(formats::pem(formats::pkcs8), encoded->view()).has_value()); + })); + BOOST_TEST(enters_a_guard([&] { BOOST_TEST( crypto::decode(formats::pem(formats::pkcs8), encoded->view()).has_value()); - }); - webcpp::test::require_enters("detail::decode_pem of pem(pkcs8), refused", [&] { - BOOST_TEST(crypto::decode(formats::pem(formats::pkcs8), key_pem).error() == + })); + BOOST_TEST(enters_a_guard([&] { + BOOST_TEST(codecs::decode(formats::pem(formats::pkcs8), key_pem).error() == codecs::error::invalid_prefix); - }); - webcpp::test::uncovered("detail::decode_pem of pem(spki)", [&] { - BOOST_TEST(crypto::decode(formats::pem(formats::spki), key_pem).has_value()); - }); + })); + std::size_t const before = webcpp::test::timing_all_entries; + BOOST_TEST(codecs::decode(formats::pem(formats::spki), key_pem).has_value()); + BOOST_TEST_EQ(webcpp::test::timing_all_entries, before); } /** Whether two results hold equal values, or the same error. */ @@ -347,8 +395,8 @@ void same_results(codecs::result const& expected, codecs::result c } /** - * crypto::decode of `text`, as a std::string, a span of characters and a vector of them, and - * codecs::decode of it give the same value, or the same error, for both PEM pairs. + * crypto::decode of `text`, as a std::string, a span of characters and a vector of them, + * codecs::decode of it and the member give the same value, or the same error, for both PEM pairs. */ void same_as_codecs_on(std::string const& text) { auto const same_key = [](toy_key const& first, toy_key const& second) { @@ -365,15 +413,23 @@ void same_as_codecs_on(std::string const& text) { same_key); same_results(in_place, crypto::decode(formats::pem(formats::spki), characters), same_key); + same_results(in_place, toy_key::decode(formats::pem(formats::spki), text), same_key); + same_results(in_place, codecs::decode(formats::pem(formats::spki), characters), + same_key); auto const private_in_place = crypto::decode(formats::pem(formats::pkcs8), text); same_results(private_in_place, codecs::decode(formats::pem(formats::pkcs8), text), same_key_pair); + same_results(private_in_place, toy_keypair::decode(formats::pem(formats::pkcs8), text), + same_key_pair); same_results(private_in_place, crypto::decode(formats::pem(formats::pkcs8), characters), same_key_pair); } -/** crypto::decode and codecs::decode give the same value, or the same error, on every text. */ +/** + * crypto::decode, codecs::decode and the member give the same value, or the same error, on every + * text. + */ void same_as_codecs() { std::string const crlf = with_crlf(key_pem); std::string const certificate = armored("CERTIFICATE", key_spki); diff --git a/test/formats_verbs_test.cpp b/test/formats_verbs_test.cpp index 2450ed6b..12a358d1 100644 --- a/test/formats_verbs_test.cpp +++ b/test/formats_verbs_test.cpp @@ -9,7 +9,9 @@ // decision 23): every form of each pair gives one encoding and decodes it back, a short span // untouched; nothing on the heap; strict decoding; the private results secret and wiped when moved // from; the two bounds, equal but on the one pair that rules otherwise, whose longer form decodes -// and re-encodes as the shorter; a moved-from key pair refused with invalid_state, nothing written; +// and re-encodes as the shorter; each pair's largest valid input, exactly its decode bound, decodes +// on every path and one byte more is codecs' input_too_long (one-verb's R9, owner decision 29); a +// moved-from key pair refused with invalid_state, nothing written; // crypto's check of the type's list, and a type crypto does not own passed to codecs untouched. // test/messages/format_refused_toy, decode_bound_missing and decode_bound_differs stop the pairs // this cannot compile. @@ -179,12 +181,6 @@ static_assert(detail::refusal_reason_v == detail::refusal_reason::no_der_ed25519_bip340); static_assert(detail::pair_accepted, toy_signature>()); -// The secrecy decode_pem reads through a requires check: absent on the public value codecs. -static_assert(!detail::value_codec_secret_v, toy_key>); -static_assert(detail::value_codec_secret_v); -static_assert(detail::value_codec_secret_v, toy_keypair>); -static_assert(!detail::value_codec_secret_v); - // Every pair of crypto's is noexcept; a pair crypto does not own is as codecs' verb is. static_assert(noexcept(crypto::encode(formats::spki, std::declval()))); static_assert(noexcept(crypto::encode(formats::pkcs8, std::declval()))); @@ -289,7 +285,52 @@ void decode_bound_past_the_encoding() { std::array longer{}; std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); BOOST_TEST(crypto::decode(formats::pkcs8, longer).error() == - crypto::error::invalid_encoding); + codecs::error::input_too_long); +} + +/** + * An input longer than its pair's decode bound is codecs' input_too_long, before the value codec + * reads a byte (owner decision 29), through crypto::decode, codecs::decode and the member: 9 bytes + * of raw, 13 of spki, 17 of pkcs8, 5 of a signature's raw. + */ +void past_the_bound() { + auto const too_long = [](auto const& decoded) { + return !decoded.has_value() && decoded.error() == codecs::error::input_too_long; + }; + std::array const longest{}; + std::span const raw_bytes = std::span(longest).first(9); + std::span const spki_bytes = std::span(longest).first(13); + std::span const signature_raw = std::span(longest).first(5); + BOOST_TEST(too_long(crypto::decode(formats::raw, raw_bytes))); + BOOST_TEST(too_long(codecs::decode(formats::raw, raw_bytes))); + BOOST_TEST(too_long(toy_key::decode(formats::raw, raw_bytes))); + BOOST_TEST(too_long(crypto::decode(formats::spki, spki_bytes))); + BOOST_TEST(too_long(codecs::decode(formats::spki, spki_bytes))); + BOOST_TEST(too_long(toy_key::decode(formats::spki, spki_bytes))); + BOOST_TEST(too_long(crypto::decode(formats::raw, raw_bytes))); + BOOST_TEST(too_long(codecs::decode(formats::raw, raw_bytes))); + BOOST_TEST(too_long(toy_keypair::decode(formats::raw, raw_bytes))); + BOOST_TEST(too_long(crypto::decode(formats::pkcs8, longest))); + BOOST_TEST(too_long(codecs::decode(formats::pkcs8, longest))); + BOOST_TEST(too_long(toy_keypair::decode(formats::pkcs8, longest))); + BOOST_TEST(too_long(crypto::decode(formats::raw, signature_raw))); + BOOST_TEST(too_long(codecs::decode(formats::raw, signature_raw))); +} + +/** + * Each pair of the toy that decodes takes its largest valid input, exactly its decode bound, on + * every path, and refuses one byte more with input_too_long (one-verb's R9): the key pair's pkcs8 + * through its 16-byte "version 2". + */ +void largest_inputs() { + crypto::test::check_largest_input, toy_key>(formats::raw, key_bytes); + crypto::test::check_largest_input, toy_key>(formats::spki, key_spki); + crypto::test::check_largest_input, toy_keypair>(formats::raw, secret_bytes); + crypto::test::check_largest_input(formats::pkcs8, + key_pair_pkcs8_v2); + crypto::test::check_largest_input, toy_point>(formats::raw, key_bytes); + crypto::test::check_largest_input, toy_signature>(formats::raw, + signature_bytes); } /** @@ -362,6 +403,8 @@ int main() { strict(); secret_results(); decode_bound_past_the_encoding(); + past_the_bound(); + largest_inputs(); moved_from_key_pair(); foreign_pairs(); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/formats_x25519_sodium_test.cpp b/test/formats_x25519_sodium_test.cpp index dd4a99a7..0e39eed3 100644 --- a/test/formats_x25519_sodium_test.cpp +++ b/test/formats_x25519_sodium_test.cpp @@ -11,14 +11,18 @@ // strictness, the secret results; a key pair's raw, its secret() and from_secret; Wycheproof's // x25519_asn_test.json (SPKI and PKCS#8: the valid and acceptable cases decode, encode again to // the same bytes and agree on the file's shared secret, or are refused with weak_public_key where -// it is all zero; the invalid ones are invalid_encoding) and x25519_pem_test.json the same way +// it is all zero; the invalid ones are invalid_encoding, or codecs' input_too_long where longer +// than the pair's decode bound, 44 or 48 bytes) and x25519_pem_test.json the same way // through pem(spki) and pem(pkcs8); round trips of random key pairs; a PEM with CRLF lines and // without its final line feed decoded, and one with text before BEGIN refused; a moved-from key -// pair refused by every private format with nothing written; and every malformed DER refused with -// invalid_encoding: Ed25519's OID, a trailing byte, a length in long form, PKCS#8 version 2 with -// the public key, each byte of a prefix changed. +// pair refused by every private format with nothing written; each pair's largest valid input, +// exactly its decode bound, decoded on every path and one byte more codecs' input_too_long +// (one-verb's R9); and every malformed DER refused: Ed25519's OID, a trailing byte, a length in +// long form, each byte of a prefix changed with invalid_encoding, PKCS#8 version 2 with the public +// key, past the PKCS#8's decode bound, with codecs' input_too_long. #include +#include #include #include #include @@ -222,6 +226,10 @@ static_assert(noexcept(public_key::decode(formats::pem(formats::spki), std::stri static_assert(noexcept(std::declval().encode(formats::pem(formats::pkcs8)))); static_assert(noexcept(keypair::decode(formats::pkcs8, std::declval()))); static_assert(noexcept(keypair::decode(formats::raw, std::declval()))); +// codecs' decode of each PEM pair is noexcept (one-verb's R10). +static_assert(noexcept(codecs::decode(formats::pem(formats::spki), + std::string_view{}))); +static_assert(noexcept(codecs::decode(formats::pem(formats::pkcs8), std::string_view{}))); } // namespace member_checks /** @@ -263,6 +271,13 @@ void every_form() { crypto::test::check_secret_result(formats::pkcs8, *key_pair); crypto::test::check_secret_result(formats::pem(formats::pkcs8), *key_pair); crypto::test::check_secret_result(formats::raw, *key_pair); + + // The decode bound is each pair's acceptance contract (one-verb's R9). + crypto::test::check_largest_input, x25519::public_key>(formats::raw, + public_key->bytes()); + crypto::test::check_largest_input, x25519::public_key>(formats::spki, spki); + crypto::test::check_largest_input, x25519::keypair>(formats::raw, secret_key); + crypto::test::check_largest_input(formats::pkcs8, pkcs8); } /** A key pair's raw is its secret() and from_secret under the format's name (design R2). */ @@ -315,10 +330,25 @@ bool agrees_as_the_file(x25519::keypair const& key_pair, x25519::public_key cons return agreed.has_value() && test::to_hex(agreed->bytes()) == shared; } +/** + * The size of the DER a case gives: its bytes, or the payload of its PEM read with `label` (0 when + * the armor refuses it). + */ +template +std::size_t der_size(Input const& input, std::string_view label) { + if constexpr (std::is_same_v) { + auto const der = codecs::decode(codecs::formats::armor(label), input); + return der ? der->size() : 0; + } else { + return input.size(); + } +} + /** * Counts one case under its result; for an invalid one, checks that a key was refused and every - * refusal is `invalid_encoding`; for the others, that both keys decoded, encode again to the - * case's input and agree as the file says. + * refusal is `invalid_encoding`, or codecs' input_too_long for a DER longer than its pair's decode + * bound (owner decision 29, derived from its length, never from a list of cases); for the others, + * that both keys decoded, encode again to the case's input and agree as the file says. */ template bool check_case(json::value const& test_case, Input const& public_input, Input const& private_input, @@ -344,9 +374,15 @@ bool check_case(json::value const& test_case, Input const& public_input, Input c auto const key_pair = crypto::decode(private_format, private_input); if (result == "invalid") { ++counts.invalid; + auto const public_expected = + crypto::test::expected_error, x25519::public_key>( + der_size(public_input, "PUBLIC KEY"), crypto::error::invalid_encoding); + auto const private_expected = + crypto::test::expected_error( + der_size(private_input, "PRIVATE KEY"), crypto::error::invalid_encoding); return (!public_key || !key_pair) && - (public_key || public_key.error() == crypto::error::invalid_encoding) && - (key_pair || key_pair.error() == crypto::error::invalid_encoding); + (public_key || public_key.error() == public_expected) && + (key_pair || key_pair.error() == private_expected); } if (result == "valid") { ++counts.valid; @@ -369,7 +405,8 @@ bool check_case(json::value const& test_case, Input const& public_input, Input c * Wycheproof's x25519_asn_test.json: each case's SPKI and PKCS#8 (ruling F24): 265 valid and 253 * acceptable cases decode, encode again to the same bytes and agree on the file's shared secret, * or refuse a public key of low order with weak_public_key; the 19 invalid ones, another curve's - * public key and a PKCS#8 without its inner OCTET STRING, are invalid_encoding. + * public key and a PKCS#8 without its inner OCTET STRING, are invalid_encoding, or codecs' + * input_too_long where longer than the pair's decode bound. */ void wycheproof_asn() { auto const document = test::wycheproof_file("/testvectors_v1/x25519_asn_test.json"); diff --git a/test/fuzz/Jamfile b/test/fuzz/Jamfile index 427936f6..ba4a3a1c 100644 --- a/test/fuzz/Jamfile +++ b/test/fuzz/Jamfile @@ -8,8 +8,9 @@ # lane fuzz, on webcpp::codecs' model (its test/fuzz/), one target per decoder, # each _fuzz.cpp a libFuzzer target whose checks are target.hpp's: no # crash, no heap, what decodes encodes back to the input (a PEM to its lines -# ended by line feeds), and, for a secret format, every buffer of crypto's -# wiped. The tests' toy PEM and hash's Base58Check (hash's design D4: hash has +# ended by line feeds), an input past its pair's decode bound input_too_long, +# and, for a secret format, every wipe leaving zero bytes, a PEM's intermediate +# in codecs' over wiped and none made past the bound. The tests' toy PEM and hash's Base58Check (hash's design D4: hash has # no fuzz lane of its own) come first; each curve adds one target per decoder, # its corpus, its line below and its name to the lane. project : requirements /webcpp/crypto//crypto ; diff --git a/test/fuzz/ed25519_pem_pkcs8_fuzz.cpp b/test/fuzz/ed25519_pem_pkcs8_fuzz.cpp index 5abe7e51..d9c811e5 100644 --- a/test/fuzz/ed25519_pem_pkcs8_fuzz.cpp +++ b/test/fuzz/ed25519_pem_pkcs8_fuzz.cpp @@ -4,10 +4,11 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The fuzz target of Ed25519's PEM of a PKCS#8 (curves/ed25519/formats.hpp): every input is a -// text decoded in place through crypto::decode, a secret format, with no heap; what decodes -// encodes back to the text's lines as the armor writes them, and the decode's buffer of the -// PKCS#8's decode bound is wiped on every path (target.hpp's fuzz_decode). +// The fuzz target of Ed25519's PEM of a PKCS#8 (curves/ed25519/formats.hpp): every input is a text +// decoded in place through crypto::decode, codecs' over, a secret format, with no heap; what +// decodes encodes back to the text's lines as the armor writes them, and codecs' intermediate, the +// payload's bytes, is wiped on every path within the PKCS#8's decode bound, none made past it, +// input_too_long (target.hpp's fuzz_decode). #include "target.hpp" diff --git a/test/fuzz/p256_pem_pkcs8_fuzz.cpp b/test/fuzz/p256_pem_pkcs8_fuzz.cpp index ea91a3d2..f9c713a5 100644 --- a/test/fuzz/p256_pem_pkcs8_fuzz.cpp +++ b/test/fuzz/p256_pem_pkcs8_fuzz.cpp @@ -5,9 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) // The fuzz target of P-256's PEM of a PKCS#8 (curves/p256/formats.hpp): every input is a text -// decoded in place through crypto::decode, a secret format, with no heap; what decodes encodes -// back to the text's lines as the armor writes them, and the decode's buffer of the PKCS#8's -// decode bound is wiped on every path (target.hpp's fuzz_decode). +// decoded in place through crypto::decode, codecs' over, a secret format, with no heap; what +// decodes encodes back to the text's lines as the armor writes them, and codecs' intermediate, the +// payload's bytes, is wiped on every path within the PKCS#8's decode bound, none made past it, +// input_too_long (target.hpp's fuzz_decode). #include "target.hpp" diff --git a/test/fuzz/secp256k1_pem_pkcs8_fuzz.cpp b/test/fuzz/secp256k1_pem_pkcs8_fuzz.cpp index b89feed3..7b1d4ce1 100644 --- a/test/fuzz/secp256k1_pem_pkcs8_fuzz.cpp +++ b/test/fuzz/secp256k1_pem_pkcs8_fuzz.cpp @@ -5,10 +5,11 @@ // https://www.boost.org/LICENSE_1_0.txt) // The fuzz target of secp256k1's PEM of a PKCS#8 (curves/secp256k1/formats.hpp): every input is a -// text decoded in place through crypto::decode, a secret format, with no heap (the key pair's -// context from secp256k1_resource.hpp's blocks); what decodes encodes back to the text's lines as -// the armor writes them, and the decode's buffer of the PKCS#8's decode bound is wiped on every -// path (target.hpp's fuzz_decode). +// text decoded in place through crypto::decode, codecs' over, a secret format, with no heap (the +// key pair's context from secp256k1_resource.hpp's blocks); what decodes encodes back to the text's +// lines as the armor writes them, and codecs' intermediate, the payload's bytes, is wiped on every +// path within the PKCS#8's decode bound, none made past it, input_too_long (target.hpp's +// fuzz_decode). #include "secp256k1_resource.hpp" #include "target.hpp" diff --git a/test/fuzz/target.hpp b/test/fuzz/target.hpp index 6e110978..d93d5f36 100644 --- a/test/fuzz/target.hpp +++ b/test/fuzz/target.hpp @@ -12,12 +12,14 @@ // binary format its bytes, a PEM its text with each carriage return before a line feed removed and // a final line feed added, the lines as the armor writes them (codecs' armor takes both line ends // and no final one, and writes line feeds). For a secret format (a secret value codec, or a secret -// value), every wipe secure's record holds must have left only zero bytes, and a PEM's decode must -// have wiped its buffer of the inner format's decode bound, on success and on error. A mismatch -// prints what failed and ends the program by a trap, which libFuzzer reports with the input and -// the replay with the test's failure. same_as_named checks a public key's default point form -// against the named form of the input's size, and same_as_named_text a PEM's against both named -// forms, for the targets of curves with point forms. +// value), every wipe secure's record holds must have left only zero bytes, and a PEM's decode +// through codecs' over must have wiped its intermediate, the payload's bytes, when the armor reads +// the text and the payload is within the inner format's decode bound, on success and on the value +// codec's refusal, and must have made none for a payload past the bound (codecs' input_too_long). +// A mismatch prints what failed and ends the program by a trap, which libFuzzer reports with the +// input and the replay with the test's failure. same_as_named checks a public key's default point +// form against the named form of the input's size, and same_as_named_text a PEM's against both +// named forms, for the targets of curves with point forms. // // The heap is counted by fuzz_allocations, which this header declares and each program defines // once: the replay, on every lane, through support/counting.hpp's replaced allocation functions @@ -30,6 +32,7 @@ #define WEBCPP_CRYPTO_TEST_FUZZ_TARGET_HPP #include +#include #include #include @@ -37,6 +40,7 @@ #include #include #include +#include #include #include @@ -161,16 +165,59 @@ struct format_parts> { /** Checks secure's wipe record after a secret call: every wipe left only zero bytes and was kept, - and, after a PEM's decode, its buffer of the inner format's decode bound was wiped. + and, after a PEM's decode, its intermediate of `required_size` bytes was wiped. - @param buffer_size The size of the buffer whose wipe is required, or 0 for none. + @param required_size The size of the wipe that must be found, or 0 for none. @param what The call, for the message. */ -inline void expect_wiped(std::size_t buffer_size, char const* what) noexcept { - fuzz_wipe_summary const wipes = fuzz_wipes(buffer_size); +inline void expect_wiped(std::size_t required_size, char const* what) noexcept { + fuzz_wipe_summary const wipes = fuzz_wipes(required_size); expect(wipes.all_kept, what); expect(wipes.not_zero == 0, what); - expect(buffer_size == 0 || wipes.of_size != 0, what); + expect(required_size == 0 || wipes.of_size != 0, what); +} + +/** + Checks secure's wipe record after a secret PEM's decode refused for a payload past its bound: + every wipe left only zero bytes and was kept, and none was of the payload's size, so no + intermediate held it. + + @param payload_size The payload's size. + @param what The call, for the message. +*/ +inline void expect_no_intermediate(std::size_t payload_size, char const* what) noexcept { + fuzz_wipe_summary const wipes = fuzz_wipes(payload_size); + expect(wipes.all_kept, what); + expect(wipes.not_zero == 0, what); + expect(wipes.of_size == 0, what); +} + +/** + Whether the value codec of `Format` and `Value` is secret: it states `secret`, and it is true. + + @tparam Format The format's type. + @tparam Value The value's type. +*/ +template +inline constexpr bool value_codec_secret = + requires { requires static_cast(codecs::value_codec::secret); }; + +/** + The size of the payload of the PEM `text` of `Inner`, read with `Inner`'s label by codecs' armor + (onto the heap: called outside the counted region), or none when the armor refuses the text. + + @tparam Inner The PEM's inner format. + @param text The text. + @return The payload's size, or none. +*/ +template +std::optional pem_payload_size(std::string_view text) { + auto const payload = + codecs::decode(codecs::formats::armor(crypto::detail::pem_label_v), text); + if (!payload) { + return std::nullopt; + } + return payload->size(); } } // namespace fuzz_detail @@ -180,7 +227,8 @@ inline void expect_wiped(std::size_t buffer_size, char const* what) noexcept { input read as a text for a PEM and as bytes otherwise, allocates nothing; what decodes encodes back through `crypto::encode(format, value)`, allocating nothing, to the input (a PEM to its lines as the armor writes them); for a secret format every wipe leaves zero bytes, and a PEM's decode - wipes its buffer. + wipes codecs' intermediate, the payload's bytes, when the armor reads the text and the payload is + within the inner format's decode bound, and makes none for a payload past it. @tparam Value The value's type. @tparam Format The format's type. @@ -191,13 +239,20 @@ template void fuzz_decode(Format format, std::span input) { using fuzz_detail::expect; using parts = fuzz_detail::format_parts; - constexpr bool secret = crypto::detail::value_codec_secret_v || - codecs::is_secret_v; - constexpr std::size_t pem_buffer_size = - parts::pem && secret ? formats::max_decode_input_size : 0; + constexpr bool secret = + fuzz_detail::value_codec_secret || codecs::is_secret_v; std::string_view const text{reinterpret_cast(input.data()), input.size()}; + // The payload a PEM holds, read before the counted region (the armor's heap form). + std::optional payload_size; + if constexpr (parts::pem) { + payload_size = fuzz_detail::pem_payload_size(text); + } + constexpr std::size_t bound = formats::max_decode_input_size; + bool const past_bound = payload_size.has_value() && *payload_size > bound; + std::size_t const intermediate_size = payload_size && !past_bound ? *payload_size : 0; if constexpr (secret) { - // The wipes since the last check, the previous input's values' among them. + // The wipes since the last check, the previous input's values' and the payload's read + // among them: every one left zero bytes. expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); } @@ -210,8 +265,17 @@ void fuzz_decode(Format format, std::span input) { } }(); expect(fuzz_allocations() == before, "the decode allocated"); + // An input past the bound, the payload of a PEM the armor reads, is codecs' input_too_long. + bool const input_past_bound = parts::pem ? past_bound : input.size() > bound; + expect(!input_past_bound || (!decoded && decoded.error() == codecs::error::input_too_long), + "an input past the bound is not input_too_long"); if constexpr (secret) { - fuzz_detail::expect_wiped(pem_buffer_size, "the decode left a buffer not wiped"); + if (past_bound) { + fuzz_detail::expect_no_intermediate(*payload_size, + "the decode made an intermediate past the bound"); + } else { + fuzz_detail::expect_wiped(intermediate_size, "the decode left a buffer not wiped"); + } } if (!decoded) { return; @@ -264,8 +328,10 @@ void same_as_named(Default const& any_form, Compressed const& compressed, /** Checks that a public key's default point form decodes a PEM text as the named forms do (design R1): a text's size names no form, so the default gives the key the named form that decodes the - text gives, or, refused by both, the error both give, the armor's own or the SPKI's - invalid_encoding, whatever the payload. + text gives, or, refused, the error the uncompressed form gives, whose decode bound is the + default's: the armor's own, the SPKI's invalid_encoding, or codecs' input_too_long past the bound. + The compressed form gives that error too, but for a payload past its own, shorter, bound, which + is its input_too_long. @tparam Value The public key's type. @tparam Default The default form's PEM format. @@ -279,16 +345,30 @@ void same_as_named(Default const& any_form, Compressed const& compressed, template void same_as_named_text(Default const& any_form, Compressed const& compressed, Uncompressed const& uncompressed, std::span input) { + using compressed_inner = fuzz_detail::format_parts::inner; + using default_inner = fuzz_detail::format_parts::inner; + using uncompressed_inner = fuzz_detail::format_parts::inner; + static_assert(formats::max_decode_input_size == + formats::max_decode_input_size); // The input's bytes are the text's characters. std::string_view const text{reinterpret_cast(input.data()), input.size()}; auto const by_default = crypto::decode(any_form, text); auto const by_compressed = crypto::decode(compressed, text); auto const by_uncompressed = crypto::decode(uncompressed, text); auto const& by_name = by_compressed ? by_compressed : by_uncompressed; + std::optional const payload_size = + fuzz_detail::pem_payload_size(text); + bool const past_compressed_bound = + payload_size.has_value() && + *payload_size > formats::max_decode_input_size; + bool const compressed_agrees = + past_compressed_bound + ? !by_compressed && by_compressed.error() == codecs::error::input_too_long + : by_default.has_value() || by_default.error() == by_compressed.error(); fuzz_detail::expect(by_default.has_value() == by_name.has_value() && (by_default ? *by_default == *by_name - : by_default.error() == by_compressed.error() && - by_default.error() == by_uncompressed.error()), + : by_default.error() == by_uncompressed.error()) && + compressed_agrees, "the default form decodes otherwise than the named one"); } diff --git a/test/fuzz/x25519_pem_pkcs8_fuzz.cpp b/test/fuzz/x25519_pem_pkcs8_fuzz.cpp index 5f2037d1..47cf01b5 100644 --- a/test/fuzz/x25519_pem_pkcs8_fuzz.cpp +++ b/test/fuzz/x25519_pem_pkcs8_fuzz.cpp @@ -5,9 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) // The fuzz target of X25519's PEM of a PKCS#8 (curves/x25519/formats.hpp): every input is a text -// decoded in place through crypto::decode, a secret format, with no heap; what decodes encodes -// back to the text's lines as the armor writes them, and the decode's buffer of the PKCS#8's -// decode bound is wiped on every path (target.hpp's fuzz_decode). +// decoded in place through crypto::decode, codecs' over, a secret format, with no heap; what +// decodes encodes back to the text's lines as the armor writes them, and codecs' intermediate, the +// payload's bytes, is wiped on every path within the PKCS#8's decode bound, none made past it, +// input_too_long (target.hpp's fuzz_decode). #include "target.hpp" diff --git a/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp b/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp index b88b3c49..126ab897 100644 --- a/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp +++ b/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp @@ -4,14 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// crypto::decode of a PEM pair of crypto's from bytes, not a text, stops at the in-place decode, -// which never hands a pair of crypto's to codecs' heap path (design R24), and with that error -// alone. +// crypto::decode of a PEM pair of crypto's from bytes, not a text, stops in codecs' typed decode, +// where the PEM's value codec, codecs' over, decodes from text (codecs' ruling R25), and with that +// error alone; its requirement names the input's type and the PEM's. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: a PEM decodes from a text: a std::string_view, or a contiguous range of char}} +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char}} // clang-format on #include "../../support/formats_toy.hpp" diff --git a/test/p256_formats_bearssl_test.cpp b/test/p256_formats_bearssl_test.cpp index e82882cd..04c7ad57 100644 --- a/test/p256_formats_bearssl_test.cpp +++ b/test/p256_formats_bearssl_test.cpp @@ -8,24 +8,26 @@ // uncompressed and the compressed point, PKCS#8 with RFC 5915's ECPrivateKey, PEM around both // through codecs' armor, the public key's raw point in both forms, the key pair's raw scalar, the // signature's raw r || s and its strict DER. The header's constants equal the DER a small builder -// writes here from the ASN.1; RFC 6979's key through every form, its compressed() the prefix of -// y's parity and x; both bounds of every pair; every form of every pair -// (support/format_checks.hpp), no heap, strictness, the secret results; BearSSL's square root of -// the compressed point on its own (x not below p, x^3 - 3x + b no square, both parities, 64 -// generated keys of each parity) and through raw and spki (Review Focus 2); BearSSL's own PKCS#8 -// encoder an oracle of the layout; every malformed input refused; Wycheproof's -// ecdh_secp256r1_ecpoint_test.json (its compressed points: tcId 2 decodes to tcId 1's point and -// agrees on its shared x, the 7 others are invalid_public_key, ruling F23), -// ecdh_secp256r1_test.json (its SPKIs, decoded then derived, each refusal of an acceptable case -// listed with its reason), ecdh_secp256r1_pem_test.json (its public PEMs through pem(spki)) and -// ecdsa_secp256r1_sha256_test.json (each DER through der: a valid case parses and encodes again to -// the same bytes, a case flagged for BER, a missing or needless zero or another encoding fault is -// invalid_signature, and an invalid case that parses does not verify); PEM with CRLF lines and -// without its final line feed decoded, with text before BEGIN refused (Review Focus 1); an RSA -// key's PEM and an empty armor refused (Review Focus 5); a moved-from key pair refused by every -// private format with nothing written (Review Focus 3); DER of r or s 0 or not below n refused, -// and a span one byte short refused untouched (Review Focus 4); the private formats refused on a -// backend whose key pairs live in WebCrypto (design D7). +// writes here from the ASN.1; RFC 6979's key through every form, its compressed() the prefix of y's +// parity and x; both bounds of every pair; every form of every pair (support/format_checks.hpp), no +// heap, strictness, the secret results; BearSSL's square root of the compressed point on its own (x +// not below p, x^3 - 3x + b no square, both parities, 64 generated keys of each parity) and through +// raw and spki (Review Focus 2); BearSSL's own PKCS#8 encoder an oracle of the layout; every +// malformed input refused; Wycheproof's ecdh_secp256r1_ecpoint_test.json (its compressed points: +// tcId 2 decodes to tcId 1's point and agrees on its shared x, the 7 others are invalid_public_key, +// ruling F23), ecdh_secp256r1_test.json (its SPKIs, decoded then derived, each refusal of an +// acceptable case listed with its reason), ecdh_secp256r1_pem_test.json (its public PEMs through +// pem(spki)) and ecdsa_secp256r1_sha256_test.json (each DER through der: a valid case parses and +// encodes again to the same bytes, a case flagged for BER, a missing or needless zero or another +// encoding fault is invalid_signature, codecs' input_too_long past 72 bytes, and an invalid case +// that parses does not verify); PEM with CRLF lines and without its final line feed decoded, with +// text before BEGIN refused (Review Focus 1); an RSA key's PEM and its DER codecs' input_too_long +// on every path, an empty armor refused (one-verb's Review Focus 4); each pair's largest valid +// input, exactly its decode bound, decoded on every path and one byte more input_too_long +// (one-verb's R9); a moved-from key pair refused by every private format with nothing written +// (Review Focus 3); DER of r or s 0 or not below n refused, and a span one byte short refused +// untouched (Review Focus 4); the private formats refused on a backend whose key pairs live in +// WebCrypto (design D7). #include #include @@ -304,6 +306,10 @@ static_assert(noexcept(std::declval().encode(formats::pem(format static_assert(noexcept(keypair::decode(formats::pkcs8, std::declval()))); static_assert(noexcept(std::declval().encode(formats::der))); static_assert(noexcept(ecdsa_signature::decode(formats::der, std::declval()))); +// codecs' decode of each PEM pair is noexcept (one-verb's R10). +static_assert(noexcept(codecs::decode(formats::pem(formats::spki), + std::string_view{}))); +static_assert(noexcept(codecs::decode(formats::pem(formats::pkcs8), std::string_view{}))); } // namespace member_checks // Every form of every pair on RFC 6979's key pair and its "test" signature: the same encoding from @@ -368,6 +374,29 @@ void every_form() { crypto::test::check_secret_result(formats::raw, pair); crypto::test::check_secret_result(formats::pkcs8, pair); crypto::test::check_secret_result(formats::pem(formats::pkcs8), pair); + + // The decode bound is each pair's acceptance contract (one-verb's R9): a public key's largest + // raw and spki are its uncompressed forms; a DER signature's, r and s of 33 bytes each. + using formats::compressed_t; + using formats::uncompressed_t; + crypto::test::check_largest_input, public_key>(formats::raw, point); + crypto::test::check_largest_input, public_key>( + formats::raw(formats::uncompressed), point); + crypto::test::check_largest_input, public_key>( + formats::raw(formats::compressed), compressed); + crypto::test::check_largest_input, public_key>(formats::spki, spki); + crypto::test::check_largest_input, public_key>( + formats::spki(formats::uncompressed), spki); + crypto::test::check_largest_input, public_key>( + formats::spki(formats::compressed), compressed_spki); + crypto::test::check_largest_input, keypair>(formats::raw, + bytes_of(data::rfc6979_scalar)); + crypto::test::check_largest_input(formats::pkcs8, pkcs8); + crypto::test::check_largest_input, ecdsa_signature>( + formats::raw, bytes_of(data::rfc6979_test)); + auto const largest_der = crypto::test::largest_der(); + BOOST_TEST_EQ(largest_der.size(), 72U); + crypto::test::check_largest_input(formats::der, largest_der); } // The default forms decode the compressed point too: raw and spki of 33 and 59 bytes give RFC @@ -473,9 +502,13 @@ void compressed_round_trips() { BOOST_TEST_GE(odd, 64); } +// Each refusal below is the value codec's error within the pair's decode bound and codecs' +// input_too_long past it (owner decision 29), derived from the input's length. void raw_refused(bytes const& point, char const* what) { auto const decoded = crypto::decode(formats::raw, point); - if (!BOOST_TEST(!decoded.has_value() && decoded.error() == error::invalid_public_key)) { + auto const expected = crypto::test::expected_error, public_key>( + point.size(), error::invalid_public_key); + if (!BOOST_TEST(!decoded.has_value() && decoded.error() == expected)) { static_cast(std::fprintf(stderr, "P-256 raw point accepted: %s\n", what)); } auto const from_bytes = public_key::from_bytes(point); @@ -484,21 +517,26 @@ void raw_refused(bytes const& point, char const* what) { void spki_refused(bytes const& spki, char const* what) { auto const decoded = crypto::decode(formats::spki, spki); - if (!BOOST_TEST(!decoded.has_value() && decoded.error() == error::invalid_encoding)) { + auto const expected = crypto::test::expected_error, public_key>( + spki.size(), error::invalid_encoding); + if (!BOOST_TEST(!decoded.has_value() && decoded.error() == expected)) { static_cast(std::fprintf(stderr, "P-256 SPKI accepted: %s\n", what)); } } void pkcs8_refused(bytes const& pkcs8, char const* what) { auto const decoded = crypto::decode(formats::pkcs8, pkcs8); - if (!BOOST_TEST(!decoded.has_value() && decoded.error() == error::invalid_encoding)) { + auto const expected = crypto::test::expected_error( + pkcs8.size(), error::invalid_encoding); + if (!BOOST_TEST(!decoded.has_value() && decoded.error() == expected)) { static_cast(std::fprintf(stderr, "P-256 PKCS#8 accepted: %s\n", what)); } } // A compressed point that is no point (Review Focus 2): x not below p, x^3 - 3x + b no square, // prefix 02 or 03 with 65 bytes, 04 with 33; each invalid_public_key through raw and from_bytes, -// invalid_encoding through spki, never a key. +// invalid_encoding through spki, never a key; past raw(compressed)'s decode bound, 33 bytes, +// codecs' input_too_long. void compressed_points_refused() { auto const with_prefix = [](std::uint8_t prefix, std::span rest) { bytes out{prefix}; @@ -530,7 +568,10 @@ void compressed_points_refused() { for (auto const& point : {x_not_below_p, no_square, long_compressed, short_uncompressed}) { spki_refused(spki_of(p256_oid(), point), "an SPKI around a point that is none"); auto const named = crypto::decode(formats::raw(formats::compressed), point); - BOOST_TEST(!named.has_value() && named.error() == error::invalid_public_key); + auto const expected = + crypto::test::expected_error, public_key>( + point.size(), error::invalid_public_key); + BOOST_TEST(!named.has_value() && named.error() == expected); } } @@ -856,7 +897,8 @@ boost::system::result derive(json::value const& test_case, public_key con // compressed form of tcId 1's point, decodes to that point, agrees on the case's shared x and // encodes again with raw(compressed) to its input; the 7 invalid ones (no square root, 349 to 355) // are invalid_public_key. Its uncompressed points: the valid ones decode and agree, the invalid -// ones are refused by the decode or after it. +// ones are refused by the decode or after it, those longer than raw's decode bound, 65 bytes, with +// codecs' input_too_long. // What one ecpoint case gave: its point's form and whether it was refused, or nothing when it // went wrong. enum class ecpoint_outcome : unsigned char { @@ -874,8 +916,12 @@ ecpoint_outcome ecpoint_case(json::value const& test_case, json::value const& tw bool const compressed = input.size() == 33; if (test::json_text(test_case.at("result")) == "invalid") { bool const refused = !decoded.has_value() || !derive(test_case, *decoded).has_value(); + // Past raw's decode bound, 65 bytes, codecs' input_too_long, derived from the length. + bool const past_bound = + input.size() > formats::max_decode_input_size, public_key>; bool const as_expected = - refused && (!compressed || decoded.error() == error::invalid_public_key); + refused && (!compressed || decoded.error() == error::invalid_public_key) && + (!past_bound || (!decoded && decoded.error() == codecs::error::input_too_long)); if (!as_expected) { return ecpoint_outcome::failed; } @@ -1103,8 +1149,10 @@ der_outcome der_case(json::value const& test_case, public_key const& key) { bool const fault = encoding_fault(test_case); if (!decoded) { bool const invalid = test::json_text(test_case.at("result")) == "invalid"; - return invalid && decoded.error() == error::invalid_signature ? der_outcome::invalid_refused - : der_outcome::failed; + auto const expected = crypto::test::expected_error( + input.size(), error::invalid_signature); + return invalid && decoded.error() == expected ? der_outcome::invalid_refused + : der_outcome::failed; } if (fault || encoded_bytes(formats::der, *decoded) != input) { return der_outcome::failed; @@ -1120,8 +1168,9 @@ der_outcome der_case(json::value const& test_case, public_key const& key) { } // Wycheproof's ecdsa_secp256r1_sha256_test.json through der: a valid case's DER parses and -// encodes again to the same bytes; a case flagged for an encoding fault is invalid_signature; an -// invalid case that parses encodes again to its bytes and does not verify under any_s. +// encodes again to the same bytes; a case flagged for an encoding fault is invalid_signature, or +// codecs' input_too_long when longer than der's decode bound, 72 bytes; an invalid case that parses +// encodes again to its bytes and does not verify under any_s. void wycheproof_der() { auto const document = test::wycheproof_file("/testvectors_v1/ecdsa_secp256r1_sha256_test.json"); std::map seen; diff --git a/test/p256_wycheproof_bearssl_test.cpp b/test/p256_wycheproof_bearssl_test.cpp index a0e4ae9f..5f6ef40d 100644 --- a/test/p256_wycheproof_bearssl_test.cpp +++ b/test/p256_wycheproof_bearssl_test.cpp @@ -4,15 +4,17 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// P-256 ECDSA on BearSSL against Wycheproof (spec 8.1): the SHA-256 vectors in the raw form, -// IEEE P1363's r || s, through crypto::verify(ecdsa_sha256, any_s, ...), and in DER through +// P-256 ECDSA on BearSSL against Wycheproof (spec 8.1): the SHA-256 vectors in the raw form, IEEE +// P1363's r || s, through crypto::verify(ecdsa_sha256, any_s, ...), and in DER through // crypto::decode(crypto::formats::der, ...) then crypto::verify, each case -// verified from its message and from its digest, with the same verdict. A valid case verifies, an -// invalid one is refused, and an acceptable one, which neither file has at its pinned commit, fails -// the test so that it is read. The valid cases whose S is high (is_low_s false) are counted: -// crypto::verify under any_s accepts both forms, as FIPS 186-5 and WebCrypto do (design D36, D9); -// verification_policies_test checks low_s_only's refusals. - +// verified from its message and from its digest, with the same verdict; a DER longer than 72 bytes, +// der's decode bound, codecs' input_too_long. A valid case verifies, an invalid one is refused, and +// an acceptable one, which neither file has at its pinned commit, fails the test so that it is +// read. The valid cases whose S is high (is_low_s false) are counted: crypto::verify under any_s +// accepts both forms, as FIPS 186-5 and WebCrypto do (design D36, D9); verification_policies_test +// checks low_s_only's refusals. + +#include #include #include #include @@ -159,10 +161,21 @@ void p1363() { } void der() { + // A DER longer than der's decode bound, 72 bytes, is codecs' input_too_long, before the + // backend reads it (owner decision 29), derived from its length. + int past_bound = 0; auto const seen = - run("ecdsa_secp256r1_sha256_test", [](std::vector const& encoded) { - return crypto::decode(crypto::formats::der, encoded); + run("ecdsa_secp256r1_sha256_test", [&](std::vector const& encoded) { + auto decoded = crypto::decode(crypto::formats::der, encoded); + if (encoded.size() > + crypto::formats::max_decode_input_size) { + ++past_bound; + BOOST_TEST(!decoded.has_value() && + decoded.error() == webcpp::codecs::error::input_too_long); + } + return decoded; }); + BOOST_TEST_GT(past_bound, 0); BOOST_TEST_EQ(seen.total, 484); BOOST_TEST_EQ(seen.valid, 174); BOOST_TEST_EQ(seen.invalid, 310); diff --git a/test/secp256k1_der_test.cpp b/test/secp256k1_der_test.cpp index ad0e382b..01dfc3fa 100644 --- a/test/secp256k1_der_test.cpp +++ b/test/secp256k1_der_test.cpp @@ -8,9 +8,9 @@ // strict DER and back through crypto::formats::der for signatures of // sign(crypto::signing_schemes::ecdsa_sha256, message), the strict decoder, // crypto::decode(formats::der, ...), against every case of Wycheproof's Bitcoin -// ECDSA vectors (BIP66's verdicts, counted per flag), every refusal of the DER encode, low-S -// normalization of a high-S signature, and is_low_s's answer on each form and on numbers out of -// range. +// ECDSA vectors (BIP66's verdicts, counted per flag; past 72 bytes, der's decode bound, codecs' +// input_too_long), every refusal of the DER encode, low-S normalization of a high-S signature, and +// is_low_s's answer on each form and on numbers out of range. #include #include @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -250,13 +251,23 @@ std::string str(json::value const& v) { return std::string(std::string_view(v.as_string())); } -// One case through the strict decoder, counted in all and under each of its flags. -void decode_case(json::value const& t, tallies& per_flag, tally& all) { +// One case through the strict decoder, counted in all and under each of its flags; a refusal is +// invalid_signature, or codecs' input_too_long for a DER longer than der's decode bound, 72 bytes +// (owner decision 29), derived from its length. +void decode_case(json::value const& t, tallies& per_flag, tally& all, int& past_bound) { auto const der = test::from_hex(str(t.at("sig"))); auto const strict_result = crypto::decode(formats::der, der); if (str(t.at("result")) == "valid") { BOOST_TEST(strict_result.has_value()); } + bool const too_long = + der.size() > formats::max_decode_input_size; + past_bound += too_long ? 1 : 0; + if (!strict_result) { + BOOST_TEST(strict_result.error() == + (too_long ? boost::system::error_code{codecs::error::input_too_long} + : boost::system::error_code{crypto::error::invalid_signature})); + } // What the strict decoder accepts is the DER its encoder writes again, byte for byte. if (strict_result) { auto const again = crypto::encode(formats::der, *strict_result); @@ -305,11 +316,13 @@ void wycheproof() { BOOST_TEST(!ec); tallies per_flag; tally all; + int past_bound = 0; for (auto const& group : doc.at("testGroups").as_array()) { for (auto const& t : group.at("tests").as_array()) { - decode_case(t, per_flag, all); + decode_case(t, per_flag, all, past_bound); } } + BOOST_TEST_GT(past_bound, 0); for (auto const& [flag, c] : per_flag) { std::cout << "wycheproof " << flag << ": cases=" << c.cases << " strict=" << c.strict << '\n'; diff --git a/test/secp256k1_formats_test.cpp b/test/secp256k1_formats_test.cpp index 3bd6ecc7..93512e47 100644 --- a/test/secp256k1_formats_test.cpp +++ b/test/secp256k1_formats_test.cpp @@ -9,22 +9,24 @@ // around the uncompressed point by default (88 bytes, secp256k1's default changed, R1) and the // compressed one (56); PKCS#8 with RFC 5915's ECPrivateKey; PEM around both through codecs' armor; // the typed x-only key's raw; a key pair's raw secret; the ECDSA signature's raw r || s and its -// strict DER (BIP66); the recoverable and the Schnorr signatures' raw. The header's constants -// equal the DER a small builder writes here from the ASN.1; the generator's key (secret 1) through -// every form; both bounds of every pair; every form of every pair (support/format_checks.hpp), no -// heap (a key pair's signing context from a resource lent as the default), strictness, the secret -// results; a stored compressed SPKI decoding by default (R1); 64 seeded key pairs round-trip; a -// Nostr key of BIP340's row 0 through raw(xonly) and back; every malformed input refused; -// Wycheproof's ECDH SPKIs (WEBCPP_TEST_WYCHEPROOF) and the keys of -// ecdsa_secp256k1_sha256_test.json through raw, spki and pem(spki); PEM with CRLF lines and -// without its final line feed decoded, with text before BEGIN refused; an RSA key's PEM and an -// empty armor refused; DER of r or s 0 or not below n refused and a short span refused untouched; -// a moved-from key pair refused by every private format with nothing written; the key pair's -// decode with a memory resource into an arena, none from the default resource, the same key and -// the same refusals as the decode without one; a pem(pkcs8) decode whose resource throws, every -// secret buffer wiped on the unwinding (the wipe record). The outside oracle: -// OpenSSL's keys, encodings and PEM text (WEBCPP_TEST_OPENSSL_ORACLE: natively and on WASI); node's -// crypto module is secp256k1_node_oracle_test.cpp's. +// strict DER (BIP66); the recoverable and the Schnorr signatures' raw. The header's constants equal +// the DER a small builder writes here from the ASN.1; the generator's key (secret 1) through every +// form; both bounds of every pair; every form of every pair (support/format_checks.hpp), no heap (a +// key pair's signing context from a resource lent as the default), strictness, the secret results; +// a stored compressed SPKI decoding by default (R1); 64 seeded key pairs round-trip; a Nostr key of +// BIP340's row 0 through raw(xonly) and back; every malformed input refused, an input past its +// pair's decode bound with codecs' input_too_long; each pair's largest valid input, exactly its +// decode bound, decoded on every path and one byte more input_too_long (one-verb's R9); +// Wycheproof's ECDH SPKIs (WEBCPP_TEST_WYCHEPROOF) and the keys of ecdsa_secp256k1_sha256_test.json +// through raw, spki and pem(spki); PEM with CRLF lines and without its final line feed decoded, +// with text before BEGIN refused; an RSA key's PEM and its DER codecs' input_too_long, an empty +// armor refused; DER of r or s 0 or not below n refused and a short span refused untouched; a +// moved-from key pair refused by every private format with nothing written; the key pair's decode +// with a memory resource into an arena, none from the default resource, the same key and the same +// refusals as the decode without one, at its bounds as codecs::decode (one-verb's Review Focus 5); +// a pem(pkcs8) decode whose resource throws, every secret buffer wiped on the unwinding (the wipe +// record). The outside oracle: OpenSSL's keys, encodings and PEM text (WEBCPP_TEST_OPENSSL_ORACLE: +// natively and on WASI); node's crypto module is secp256k1_node_oracle_test.cpp's. #include #include @@ -281,6 +283,11 @@ void constants() { test::to_hex(signed_values.schnorr.bytes())); } +/** Whether the value codec of `Format` and `Value` states its decode bound. */ +template +concept states_decode_bound = + requires { codecs::value_codec::max_decode_input_size; }; + // Both bounds of every pair, through formats::max_encoded_size and formats::max_decode_input_size // (owner decision 23), equal; raw(xonly) of a public key encodes only and states the first alone; // the results' types; the PEM results' capacity, codecs' bound of the armor over every label, and @@ -303,7 +310,7 @@ void bounds() { static_assert(max_encoded_size, public_key> == 65); static_assert(max_decode_input_size, public_key> == 65); static_assert(max_encoded_size, public_key> == 32); - static_assert(!crypto::detail::states_decode_bound_v, public_key>); + static_assert(!states_decode_bound, public_key>); static_assert(max_encoded_size, public_key> == 88); static_assert(max_decode_input_size, public_key> == 88); static_assert(max_encoded_size, public_key> == 56); @@ -466,6 +473,11 @@ static_assert( decltype(keypair::decode(formats::pkcs8, std::declval()))>); static_assert(noexcept(std::declval().encode(formats::der))); static_assert(noexcept(ecdsa_signature::decode(formats::der, std::declval()))); +// codecs' decode of a PEM pair is noexcept but for a key pair's, whose context the default +// resource allocates (one-verb's R10). +static_assert(noexcept(codecs::decode(formats::pem(formats::spki), + std::string_view{}))); +static_assert(!noexcept(codecs::decode(formats::pem(formats::pkcs8), std::string_view{}))); } // namespace member_checks // Every form of every pair on the generator's key pair and its signatures: the same encoding from @@ -564,6 +576,34 @@ void every_form() { crypto::test::check_secret_result(formats::raw, pair); crypto::test::check_secret_result(formats::pkcs8, pair); crypto::test::check_secret_result(formats::pem(formats::pkcs8), pair); + + // The decode bound is each pair's acceptance contract (one-verb's R9): a public key's largest + // raw and spki are its uncompressed forms; a DER signature's, r and s of 33 bytes each. + using formats::compressed_t; + using formats::uncompressed_t; + crypto::test::check_largest_input, public_key>(formats::raw, point); + crypto::test::check_largest_input, public_key>( + formats::raw(formats::uncompressed), point); + crypto::test::check_largest_input, public_key>( + formats::raw(formats::compressed), compressed); + crypto::test::check_largest_input, public_key>(formats::spki, spki); + crypto::test::check_largest_input, public_key>( + formats::spki(formats::uncompressed), spki); + crypto::test::check_largest_input, public_key>( + formats::spki(formats::compressed), compressed_spki); + crypto::test::check_largest_input, xonly_public_key>(formats::raw, x); + crypto::test::check_largest_input, xonly_public_key>( + formats::raw(formats::xonly), x); + crypto::test::check_largest_input, keypair>(formats::raw, secret_one()); + crypto::test::check_largest_input(formats::pkcs8, pkcs8); + crypto::test::check_largest_input, ecdsa_signature>(formats::raw, ecdsa_bytes); + auto const largest_der = crypto::test::largest_der(); + BOOST_TEST_EQ(largest_der.size(), 72U); + crypto::test::check_largest_input(formats::der, largest_der); + crypto::test::check_largest_input, recoverable_signature>( + formats::raw, bytes_of(signed_values.recoverable.bytes())); + crypto::test::check_largest_input, schnorr_signature>( + formats::raw, bytes_of(signed_values.schnorr.bytes())); } // The default forms decode the compressed point too: a stored compressed SPKI of 56 bytes, as the @@ -617,8 +657,9 @@ void xonly_forms() { auto const short_key = crypto::decode(formats::raw, std::span(nostr).first(31)); BOOST_TEST(!short_key && short_key.error() == error::invalid_public_key); + // Past raw's decode bound, 32 bytes: codecs' input_too_long (owner decision 29). auto const long_key = crypto::decode(formats::raw, cat({nostr, {0x00}})); - BOOST_TEST(!long_key && long_key.error() == error::invalid_public_key); + BOOST_TEST(!long_key && long_key.error() == codecs::error::input_too_long); } // One public key: its raw, SPKI and PEM in both forms and its x-only key, through the free verbs @@ -699,26 +740,31 @@ void round_trips() { } } +// Each refusal below is the value codec's error within the pair's decode bound and codecs' +// input_too_long past it (owner decision 29), derived from the input's length. void refused_spki(std::string const& label, bytes const& encoding) { auto const decoded = crypto::decode(formats::spki, encoding); - if (!BOOST_TEST(decoded.has_error()) || - !BOOST_TEST(decoded.error() == error::invalid_encoding)) { + auto const expected = crypto::test::expected_error, public_key>( + encoding.size(), error::invalid_encoding); + if (!BOOST_TEST(decoded.has_error()) || !BOOST_TEST(decoded.error() == expected)) { BOOST_ERROR(label.c_str()); } } void refused_pkcs8(std::string const& label, bytes const& encoding) { auto const decoded = crypto::decode(formats::pkcs8, encoding); - if (!BOOST_TEST(decoded.has_error()) || - !BOOST_TEST(decoded.error() == error::invalid_encoding)) { + auto const expected = crypto::test::expected_error( + encoding.size(), error::invalid_encoding); + if (!BOOST_TEST(decoded.has_error()) || !BOOST_TEST(decoded.error() == expected)) { BOOST_ERROR(label.c_str()); } } void refused_raw(std::string const& label, bytes const& point) { auto const decoded = crypto::decode(formats::raw, point); - if (!BOOST_TEST(decoded.has_error()) || - !BOOST_TEST(decoded.error() == error::invalid_public_key)) { + auto const expected = crypto::test::expected_error, public_key>( + point.size(), error::invalid_public_key); + if (!BOOST_TEST(decoded.has_error()) || !BOOST_TEST(decoded.error() == expected)) { BOOST_ERROR(label.c_str()); } } @@ -962,6 +1008,65 @@ void decode_into_arena() { } } +// The key pair's decode with a memory resource at its bounds (one-verb's Review Focus 5, design +// R13): a valid PEM takes its context from the arena and nothing from the heap, the DER its armor +// wrote (135 bytes) wiped; a payload of 136 bytes is codecs' input_too_long, as codecs::decode +// gives it, with nothing taken from the arena; a bad base64 symbol is the armor's +// invalid_character; a raw of 33 bytes and a pkcs8 of 136 are input_too_long, before the detail +// decode reads them. +void resource_member_bounds() { + auto const pair = generator_pair(); + auto const pkcs8 = encoded_bytes(formats::pkcs8, pair); + auto const text = crypto::encode(formats::pem(formats::pkcs8), pair); + if (!BOOST_TEST(text.has_value()) || !BOOST_TEST_EQ(pkcs8.size(), 135U)) { + return; + } + { + counting_arena arena; + test::clear_wipes(); + std::size_t const before = test::allocations(); + auto const decoded = keypair::decode(formats::pem(formats::pkcs8), text->view(), &arena); + BOOST_TEST_EQ(test::allocations(), before); + BOOST_TEST_EQ(arena.allocated, 1U); + BOOST_TEST(same_pair(decoded, pair, secret_one())); + // The codecs::secret_bytes<135> the armor wrote, wiped when it goes and by each move + // that hands it out of codecs' decode, every wipe leaving zero bytes. + std::vector const sizes = test::wiped_sizes(); + BOOST_TEST_GE(std::ranges::count(sizes, std::size_t{135}), 1); + } + auto const refused_as_codecs = [](std::string const& label, std::string_view input, + boost::system::error_code expected) { + counting_arena arena; + std::size_t const before = test::allocations(); + auto const with_resource = keypair::decode(formats::pem(formats::pkcs8), input, &arena); + BOOST_TEST_EQ(test::allocations(), before); + auto const through_codecs = codecs::decode(formats::pem(formats::pkcs8), input); + if (!BOOST_TEST(!with_resource.has_value() && with_resource.error() == expected && + !through_codecs.has_value() && through_codecs.error() == expected)) { + std::cerr << "refused otherwise: " << label << '\n'; + } + BOOST_TEST_EQ(arena.allocated, 0U); + }; + bytes longer = pkcs8; + longer.push_back(0); + auto const longer_text = codecs::encode(codecs::formats::armor("PRIVATE KEY"), longer, + codecs::tokens::return_string); + if (BOOST_TEST(longer_text.has_value())) { + refused_as_codecs("a payload of 136 bytes", *longer_text, codecs::error::input_too_long); + } + std::string bad_symbol(text->view()); + constexpr std::size_t first_symbol = std::string_view{"-----BEGIN PRIVATE KEY-----\n"}.size(); + bad_symbol[first_symbol] = '*'; + refused_as_codecs("a bad base64 symbol", bad_symbol, codecs::error::invalid_character); + + counting_arena arena; + auto const raw = keypair::decode(formats::raw, bytes(33, 1), &arena); + BOOST_TEST(!raw.has_value() && raw.error() == codecs::error::input_too_long); + auto const direct = keypair::decode(formats::pkcs8, longer, &arena); + BOOST_TEST(!direct.has_value() && direct.error() == codecs::error::input_too_long); + BOOST_TEST_EQ(arena.allocated, 0U); +} + // What the decode without a resource refuses, the decode with one refuses with the same error, // every block it took given back. template @@ -1009,8 +1114,8 @@ void arena_refusals() { #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS // A pem(pkcs8) decode whose resource throws std::bad_alloc, the default one and one given: the // exception reaches the caller, and every secret buffer was wiped on the unwinding: the DER the -// armor wrote (135 bytes, crypto's RAII buffer), the secret's copy and the context's seed (32 -// each), every wipe leaving zero bytes. +// armor wrote (135 bytes: codecs' intermediate, or the member's codecs::secret_bytes), the +// secret's copy and the context's seed (32 each), every wipe leaving zero bytes. void pem_pkcs8_throwing_resource() { auto const pair = generator_pair(); auto const text = crypto::encode(formats::pem(formats::pkcs8), pair); @@ -1035,7 +1140,13 @@ void pem_pkcs8_throwing_resource() { } BOOST_TEST(threw); std::vector const sizes = test::wiped_sizes(); - BOOST_TEST_EQ(std::ranges::count(sizes, std::size_t{135}), 1); + // codecs' intermediate is wiped once; the member's codecs::secret_bytes<135> is wiped by + // each move that hands it out of codecs' decode too, every one leaving zero bytes. + if (lent) { + BOOST_TEST_EQ(std::ranges::count(sizes, std::size_t{135}), 1); + } else { + BOOST_TEST_GE(std::ranges::count(sizes, std::size_t{135}), 1); + } BOOST_TEST_GE(std::ranges::count(sizes, std::size_t{32}), 2); } } @@ -1050,7 +1161,8 @@ struct spki_counts { }; // One SPKI of the ECDH file: refused unless it is in one of the two forms and its point parses -// with libsecp256k1's parser; decoded, it encodes again to the same bytes in its form. +// with libsecp256k1's parser, with invalid_encoding, or codecs' input_too_long past spki's decode +// bound, 88 bytes; decoded, it encodes again to the same bytes in its form. void ecdh_spki_case(std::string const& label, std::string_view hex, spki_counts& counts) { constexpr std::string_view uncompressed_prefix = "3056301006072a8648ce3d020106052b8104000a034200"; @@ -1076,8 +1188,12 @@ void ecdh_spki_case(std::string const& label, std::string_view hex, spki_counts& if (!BOOST_TEST(again == encoding)) { BOOST_ERROR(label.c_str()); } - } else if (!BOOST_TEST(result.has_error() && result.error() == error::invalid_encoding)) { - BOOST_ERROR(label.c_str()); + } else { + auto const expected = crypto::test::expected_error, public_key>( + encoding.size(), error::invalid_encoding); + if (!BOOST_TEST(result.has_error() && result.error() == expected)) { + BOOST_ERROR(label.c_str()); + } } } @@ -1287,6 +1403,7 @@ int main() { moved_from_key_pair(); decode_into_arena(); arena_refusals(); + resource_member_bounds(); #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS pem_pkcs8_throwing_resource(); #endif diff --git a/test/secp256k1_keys_test.cpp b/test/secp256k1_keys_test.cpp index ec36b2be..81adcef5 100644 --- a/test/secp256k1_keys_test.cpp +++ b/test/secp256k1_keys_test.cpp @@ -6,13 +6,15 @@ // secp256k1's typed public key in both SEC1 forms and its x-only form: the generator's first // multiples are made and give their bytes back, compressed and uncompressed, and a key pair's -// public key is the one made from either of its forms; every -// length but 33 and 65, every prefix but 02, 03 and 04 (X9.62's hybrid 06 and 07 with a valid -// point, which libsecp256k1 alone takes, among them), an x not below the field's prime and an -// x with no y are invalid_public_key to public_key::from_bytes and to the raw format's decode; -// the multiples go through crypto::formats::raw in each form (uncompressed by default, compressed, -// x-only to encode) both ways; keys order as their compressed bytes. +// public key is the one made from either of its forms; every length but 33 and 65, every prefix but +// 02, 03 and 04 (X9.62's hybrid 06 and 07 with a valid point, which libsecp256k1 alone takes, among +// them), an x not below the field's prime and an x with no y are invalid_public_key to +// public_key::from_bytes and to the raw format's decode, but a length past the raw format's decode +// bound, 65, which that decode refuses with codecs' input_too_long before the backend reads it +// (owner decision 29); the multiples go through crypto::formats::raw in each form (uncompressed by +// default, compressed, x-only to encode) both ways; keys order as their compressed bytes. +#include #include #include #include @@ -22,6 +24,7 @@ #include "support/hex.hpp" #include +#include #include #include @@ -82,8 +85,11 @@ void refused(std::string const& label, std::span encoded) { BOOST_ERROR(label.c_str()); } auto const decoded = crypto::decode(formats::raw, encoded); - if (!BOOST_TEST(decoded.has_error()) || - !BOOST_TEST(decoded.error() == crypto::error::invalid_public_key)) { + auto const expected = + encoded.size() > formats::max_decode_input_size, secp::public_key> + ? boost::system::error_code{webcpp::codecs::error::input_too_long} + : boost::system::error_code{crypto::error::invalid_public_key}; + if (!BOOST_TEST(decoded.has_error()) || !BOOST_TEST(decoded.error() == expected)) { BOOST_ERROR(label.c_str()); } } diff --git a/test/support/ec_formats.hpp b/test/support/ec_formats.hpp index c3fc36d8..bc1e13e3 100644 --- a/test/support/ec_formats.hpp +++ b/test/support/ec_formats.hpp @@ -8,10 +8,11 @@ // that writes RFC 5480's SPKI, RFC 5915's ECPrivateKey inside PKCS#8 and an ECDSA-Sig-Value from // the ASN.1, so that a curve's constants are checked against something they were not copied from; // the default point forms taking both sizes (check_default_forms_take_both); a PEM payload larger -// than the type's longest DER (check_pem_payload_refused, Review Focus 5); and the DER of an ECDSA -// signature, parameterised by the curve's order (check_der_signature, Review Focus 4): out of -// range, a short span, every length of r and s. It includes support/format_checks.hpp, whose rule -// it keeps: a program includes it once. +// than the type's longest DER, codecs' input_too_long on every path as the same DER given directly +// is (check_pem_payload_refused, one-verb's Review Focus 4); and the DER of an ECDSA signature, +// parameterised by the curve's order (check_der_signature, Review Focus 4): out of range, a short +// span, every length of r and s, a DER past 72 bytes input_too_long. It includes +// support/format_checks.hpp, whose rule it keeps: a program includes it once. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_EC_FORMATS_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_EC_FORMATS_HPP @@ -186,7 +187,8 @@ Signature signature_of(std::span signature_bytes) { /** * The default forms decode the compressed point too: raw of 33 bytes, `compressed_spki` (an SPKI * around `key`'s compressed point) and the PEM of the compressed form give `key`, through the - * verbs, `from_bytes` and the member; the named forms take their own size alone. + * verbs, `from_bytes` and the member; the named forms take their own size alone, the + * uncompressed form past the compressed form's decode bound codecs' input_too_long. */ template void check_default_forms_take_both(PublicKey const& key, bytes const& compressed_spki) { @@ -208,28 +210,33 @@ void check_default_forms_take_both(PublicKey const& key, bytes const& compressed auto const spki = encoded_bytes(formats::spki, key); auto const named_compressed = crypto::decode(formats::raw(formats::compressed), point); - BOOST_TEST(!named_compressed && named_compressed.error() == crypto::error::invalid_public_key); + BOOST_TEST(!named_compressed && named_compressed.error() == codecs::error::input_too_long); auto const named_uncompressed = crypto::decode(formats::raw(formats::uncompressed), compressed); BOOST_TEST(!named_uncompressed && named_uncompressed.error() == crypto::error::invalid_public_key); auto const spki_compressed = crypto::decode(formats::spki(formats::compressed), spki); - BOOST_TEST(!spki_compressed && spki_compressed.error() == crypto::error::invalid_encoding); + BOOST_TEST(!spki_compressed && spki_compressed.error() == codecs::error::input_too_long); auto const spki_uncompressed = crypto::decode(formats::spki(formats::uncompressed), compressed_spki); BOOST_TEST(!spki_uncompressed && spki_uncompressed.error() == crypto::error::invalid_encoding); } /** - * A PEM whose payload is larger than the type's longest DER (Review Focus 5): an RSA key's SPKI - * of 294 bytes labelled PUBLIC KEY, and an armor with no payload, are invalid_encoding, with - * nothing on the heap. + * A PEM whose payload is larger than the type's longest DER (one-verb's Review Focus 4): an RSA + * key's SPKI of 294 bytes labelled PUBLIC KEY is codecs' input_too_long through crypto::decode, + * codecs::decode and the member, with nothing on the heap, and so is the same DER given directly + * to codecs::decode; no intermediate holds it, so nothing is written past the bound (the fuzz + * lane's address sanitizer reads that). An armor with no payload reaches the value codec: its + * invalid_encoding. */ template void check_pem_payload_refused() { std::size_t const before = webcpp::test::allocations(); auto const rsa = crypto::decode(formats::pem(formats::spki), rsa_pem); + auto const rsa_codecs = codecs::decode(formats::pem(formats::spki), rsa_pem); + auto const rsa_member = PublicKey::decode(formats::pem(formats::spki), rsa_pem); std::string_view const empty = "-----BEGIN PUBLIC KEY-----\n-----END PUBLIC KEY-----\n"; auto const nothing = crypto::decode(formats::pem(formats::spki), empty); std::string_view const empty_private = @@ -237,15 +244,33 @@ void check_pem_payload_refused() { auto const no_pair = crypto::decode(formats::pem(formats::pkcs8), empty_private); std::size_t const after = webcpp::test::allocations(); BOOST_TEST_EQ(after, before); - BOOST_TEST(!rsa.has_value() && rsa.error() == crypto::error::invalid_encoding); + BOOST_TEST(!rsa.has_value() && rsa.error() == codecs::error::input_too_long); + BOOST_TEST(!rsa_codecs.has_value() && rsa_codecs.error() == codecs::error::input_too_long); + BOOST_TEST(!rsa_member.has_value() && rsa_member.error() == codecs::error::input_too_long); BOOST_TEST(!nothing.has_value() && nothing.error() == crypto::error::invalid_encoding); BOOST_TEST(!no_pair.has_value() && no_pair.error() == crypto::error::invalid_encoding); auto const rsa_der = codecs::decode(codecs::formats::armor("PUBLIC KEY"), rsa_pem); if (BOOST_TEST(rsa_der.has_value())) { BOOST_TEST_EQ(rsa_der->size(), 294U); + std::span const der(*rsa_der); + std::size_t const before_direct = webcpp::test::allocations(); + auto const direct = codecs::decode(formats::spki, der); + BOOST_TEST_EQ(webcpp::test::allocations(), before_direct); + BOOST_TEST(!direct.has_value() && direct.error() == codecs::error::input_too_long); } } +/** + * The DER of a signature whose r and s both have their high bit set, so that each takes 33 bytes: + * 72 bytes, the longest strict DER of an ECDSA signature over a 256-bit curve, its `der` pair's + * decode bound. + */ +template +bytes largest_der() { + return encoded_bytes(formats::der, + signature_of(joined(bytes(32, 0x80), bytes(32, 0x80)))); +} + /** * A signature out of range given to DER (Review Focus 4): r = 0, s = 0, r = n, s = n, r all ones * (`valid`'s other half beside each) are invalid_signature from encode, with nothing written, also @@ -324,8 +349,9 @@ inline bytes signature_of_length(std::size_t significant, std::uint8_t top) { /** * Every length of r and s, from 1 byte to 33 with the leading zero: the exact size is 6 + len(r) - * + len(s), from 8 to 72, and the DER the builder's; nothing, more than 72 bytes, a needless zero - * byte and a byte after the SEQUENCE are refused. + * + len(s), from 8 to 72, and the DER the builder's; nothing, a needless zero byte and a byte + * after the SEQUENCE are refused with invalid_signature, more than 72 bytes with codecs' + * input_too_long. */ template void check_der_lengths() { @@ -354,7 +380,7 @@ void check_der_lengths() { BOOST_TEST(crypto::decode(formats::der, bytes{}).error() == crypto::error::invalid_signature); BOOST_TEST(crypto::decode(formats::der, bytes(73, 0x30)).error() == - crypto::error::invalid_signature); + codecs::error::input_too_long); auto padded = der_of(joined(one, one)); padded = cat({{0x30, 0x07, 0x02, 0x02, 0x00, 0x01}, bytes(padded.begin() + 4, padded.end())}); BOOST_TEST(crypto::decode(formats::der, padded).error() == diff --git a/test/support/format_checks.hpp b/test/support/format_checks.hpp index 3cb01eef..8f927b4d 100644 --- a/test/support/format_checks.hpp +++ b/test/support/format_checks.hpp @@ -9,13 +9,16 @@ // the value back, a short span is refused untouched (check_every_form); nothing is allocated // (check_no_heap); every change of a valid encoding is refused or is the encoding of what it // decodes to (check_strict); a private result is a secret type, move-only and wiped when moved from -// (check_secret_result). The checks every curve's key pairs and keys share follow: a DER's framing -// refused (check_der_framing), a PEM as Windows and OpenSSL's tools write it (check_pem_variants), -// the label a PEM is read and written with (check_pem_labels), and a moved-from key pair given to -// every private format (check_moved_from_key_pair), with the small helpers they need (bytes_of, -// all_untouched, replaced, encoded_bytes). A program that includes this header is built with -// WEBCPP_SECURE_TEST_WIPE_RECORD, and includes it once: it defines the allocation counter -// (support/counting.hpp) and the wipe record (support/wipe_record.hpp). +// (check_secret_result); the pair's decode bound is its acceptance contract, its largest valid +// input decoding on every path and one byte more codecs' input_too_long (check_largest_input, +// one-verb's R9). The checks every curve's key pairs and keys share follow: a DER's framing +// refused, each case's error derived from its length against the pair's decode bound +// (check_der_framing, expected_error), a PEM as Windows and OpenSSL's tools write it +// (check_pem_variants), the label a PEM is read and written with (check_pem_labels), and a +// moved-from key pair given to every private format (check_moved_from_key_pair), with the small +// helpers they need (bytes_of, all_untouched, replaced, encoded_bytes). A program that includes +// this header is built with WEBCPP_SECURE_TEST_WIPE_RECORD, and includes it once: it defines the +// allocation counter (support/counting.hpp) and the wipe record (support/wipe_record.hpp). #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_FORMAT_CHECKS_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_FORMAT_CHECKS_HPP @@ -24,6 +27,7 @@ #include "wipe_record.hpp" #include +#include #include #include @@ -346,30 +350,102 @@ void check_refused(Format const& format, std::span encoding, } /** - * Checks that a DER whose framing is changed is refused by `crypto::decode` with - * `expected`: `valid`, which decodes, with a byte after it, a byte short, nothing, its outer - * SEQUENCE's length in long form (which BER allows and DER does not; `valid` is shorter than 128 - * bytes), and each of its first `prefix_size` bytes changed. + * The error `crypto::decode` gives for a refused input of `size` bytes in `Format`: codecs' + * input_too_long past the pair's decode bound, before the value codec reads a byte (owner decision + * 29), else `within_bound`, the value codec's own. + */ +template +boost::system::error_code expected_error(std::size_t size, boost::system::error_code within_bound) { + if (size > formats::max_decode_input_size) { + return codecs::error::input_too_long; + } + return within_bound; +} + +/** + * Checks that `Value::decode(format, input)` gives what `expected` takes, when `Value` has the + * member decode for the input; nothing otherwise. + */ +template +void check_member_decode(Format const& format, Input const& input, Expected const& expected) { + if constexpr (requires { Value::decode(format, input); }) { + BOOST_TEST(expected(Value::decode(format, input))); + } +} + +/** + * Checks the pair's acceptance contract (one-verb's R9): `largest`, exactly + * `formats::max_decode_input_size` bytes, decodes through `crypto::decode`, + * `codecs::decode` and the member, and, for `spki` and `pkcs8`, as the payload of `pem(format)` + * through `codecs::decode` and the member; `largest` with one byte appended is codecs' + * input_too_long on every one of those paths. + */ +template +void check_largest_input(Format format, std::span largest) { + BOOST_TEST_EQ(largest.size(), (formats::max_decode_input_size)); + std::vector longer(largest.begin(), largest.end()); + longer.push_back(0); + std::span const past(longer); + auto const decodes = [](auto const& decoded) { return decoded.has_value(); }; + auto const too_long = [](auto const& decoded) { + return !decoded.has_value() && decoded.error() == codecs::error::input_too_long; + }; + + BOOST_TEST(decodes(crypto::decode(format, largest))); + BOOST_TEST(decodes(codecs::decode(format, largest))); + check_member_decode(format, largest, decodes); + BOOST_TEST(too_long(crypto::decode(format, past))); + BOOST_TEST(too_long(codecs::decode(format, past))); + check_member_decode(format, past, too_long); + + if constexpr (crypto::detail::is_pem_inner_v) { + auto const pem = formats::pem(format); + auto const armored = [](std::span der) { + auto const text = + codecs::encode(codecs::formats::armor(crypto::detail::pem_label_v), der, + codecs::tokens::return_string); + BOOST_TEST(text.has_value()); + return text ? *text : std::string{}; + }; + std::string const largest_text = armored(largest); + std::string const past_text = armored(past); + BOOST_TEST(decodes(codecs::decode(pem, std::string_view{largest_text}))); + check_member_decode(pem, std::string_view{largest_text}, decodes); + BOOST_TEST(too_long(codecs::decode(pem, std::string_view{past_text}))); + check_member_decode(pem, std::string_view{past_text}, too_long); + } +} + +/** + * Checks that a DER whose framing is changed is refused by `crypto::decode`: `valid`, which + * decodes, with a byte after it, a byte short, nothing, its outer SEQUENCE's length in long form + * (which BER allows and DER does not; `valid` is shorter than 128 bytes), and each of its first + * `prefix_size` bytes changed. Each case's error is `expected` within the pair's decode bound and + * codecs' input_too_long past it (`expected_error`). */ template void check_der_framing(Format const& format, std::span valid, std::size_t prefix_size, boost::system::error_code expected) { + auto const refused = [&](std::span input, char const* what) { + check_refused(format, input, expected_error(input.size(), expected), + what); + }; BOOST_TEST(crypto::decode(format, valid).has_value()); std::vector longer(valid.begin(), valid.end()); longer.push_back(0); - check_refused(format, longer, expected, "a trailing byte"); - check_refused(format, valid.first(valid.size() - 1), expected, "a byte short"); - check_refused(format, {}, expected, "nothing"); + refused(longer, "a trailing byte"); + refused(valid.first(valid.size() - 1), "a byte short"); + refused({}, "nothing"); if (BOOST_TEST(valid.size() >= 2 && valid[1] < 0x80U)) { std::vector long_form(valid.begin(), valid.end()); long_form[1] = 0x81; long_form.insert(long_form.begin() + 2, valid[1]); - check_refused(format, long_form, expected, "a length in long form"); + refused(long_form, "a length in long form"); } for (std::size_t at = 0; at < prefix_size; ++at) { std::vector changed(valid.begin(), valid.end()); changed[at] ^= 0x01U; - check_refused(format, changed, expected, "a prefix byte changed"); + refused(changed, "a prefix byte changed"); } } diff --git a/test/support/rfc8410_formats.hpp b/test/support/rfc8410_formats.hpp index 4c5c991e..ccca047e 100644 --- a/test/support/rfc8410_formats.hpp +++ b/test/support/rfc8410_formats.hpp @@ -6,18 +6,20 @@ // The malformed DER of RFC 8410's keys, which Ed25519's and X25519's formats tests share (design // D4, D30): an SPKI of 44 bytes with a 12-byte prefix and a PKCS#8 of 48 bytes with a 16-byte -// prefix, each refused with invalid_encoding when its framing changes -// (support/format_checks.hpp's check_der_framing), when it names the curve's 448-bit sibling, and, -// for the PKCS#8, when it is version 2 (RFC 5958's OneAsymmetricKey with the public key: 30 51, 83 -// bytes, the size design's "Deferred: PKCS#8 v2" gives, past today's decode bound) or marked -// version 2 without the public key. It includes support/format_checks.hpp, whose rule it keeps: a -// program includes it once. +// prefix, each refused when its framing changes (support/format_checks.hpp's check_der_framing), +// when it names the curve's 448-bit sibling, and, for the PKCS#8, when it is version 2 (RFC 5958's +// OneAsymmetricKey with the public key: 30 51, 83 bytes, the size design's "Deferred: PKCS#8 v2" +// gives, past today's decode bound, so codecs' input_too_long) or marked version 2 without the +// public key; invalid_encoding within the bound, input_too_long past it. It includes +// support/format_checks.hpp, whose rule it keeps: a program includes it once. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_RFC8410_FORMATS_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_RFC8410_FORMATS_HPP #include "format_checks.hpp" +#include +#include #include #include @@ -27,6 +29,7 @@ #include #include #include +#include #include namespace webcpp::crypto::test { @@ -38,10 +41,13 @@ inline constexpr std::size_t rfc8410_spki_prefix = 12; inline constexpr std::size_t rfc8410_pkcs8_prefix = 16; /** - * Checks that every malformed DER of a key of RFC 8410 is invalid_encoding: `spki` and `pkcs8`, - * a valid SPKI and PKCS#8 of the curve, with a changed framing; with `sibling`, the last byte of - * the OID of the curve's 448-bit sibling (1.3.101.113 for Ed448, 1.3.101.111 for X448), in place - * of the curve's; and, for the PKCS#8, version 2 with `public_key` and marked version 2 alone. + * Checks that every malformed DER of a key of RFC 8410 is refused: `spki` and `pkcs8`, a valid + * SPKI and PKCS#8 of the curve, with a changed framing; with `sibling`, the last byte of the OID + * of the curve's 448-bit sibling (1.3.101.113 for Ed448, 1.3.101.111 for X448), in place of the + * curve's; and, for the PKCS#8, version 2 with `public_key` and marked version 2 alone. Each is + * invalid_encoding within the pair's decode bound and codecs' input_too_long past it + * (`expected_error`): the version 2 with the public key, 83 bytes, is past the PKCS#8's 48, + * directly and through `pem(pkcs8)`. */ template void check_rfc8410_der(std::span spki, std::span pkcs8, @@ -57,8 +63,18 @@ void check_rfc8410_der(std::span spki, std::span(formats::pkcs8, version2, crypto::error::invalid_encoding, - "PKCS#8 version 2 with the public key"); + check_refused( + formats::pkcs8, version2, + expected_error(version2.size(), crypto::error::invalid_encoding), + "PKCS#8 version 2 with the public key"); + auto const version2_text = codecs::encode(codecs::formats::armor("PRIVATE KEY"), version2, + codecs::tokens::return_string); + if (BOOST_TEST(version2_text.has_value())) { + auto const through_pem = + codecs::decode(formats::pem(formats::pkcs8), std::string_view{*version2_text}); + BOOST_TEST(!through_pem.has_value() && + through_pem.error() == codecs::error::input_too_long); + } std::vector version1_marked_2(pkcs8.begin(), pkcs8.end()); version1_marked_2[4] = 0x01; check_refused(formats::pkcs8, version1_marked_2, crypto::error::invalid_encoding, From ad246df07a96e39a44984f818e2fd0166f24a7cc Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 22:02:25 -0300 Subject: [PATCH 02/25] crypto: the fuzz Jamfile's comment lint fix --- test/fuzz/Jamfile | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/fuzz/Jamfile b/test/fuzz/Jamfile index ba4a3a1c..180ee25c 100644 --- a/test/fuzz/Jamfile +++ b/test/fuzz/Jamfile @@ -10,9 +10,10 @@ # crash, no heap, what decodes encodes back to the input (a PEM to its lines # ended by line feeds), an input past its pair's decode bound input_too_long, # and, for a secret format, every wipe leaving zero bytes, a PEM's intermediate -# in codecs' over wiped and none made past the bound. The tests' toy PEM and hash's Base58Check (hash's design D4: hash has -# no fuzz lane of its own) come first; each curve adds one target per decoder, -# its corpus, its line below and its name to the lane. +# in codecs' over wiped and none made past the bound. The tests' toy PEM and +# hash's Base58Check (hash's design D4: hash has no fuzz lane of its own) come +# first; each curve adds one target per decoder, its corpus, its line below and +# its name to the lane. project : requirements /webcpp/crypto//crypto ; import webcpp regex ; From 346ec6f5d1b3e642a24121cb001f09f44292cf50 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 22:23:36 -0300 Subject: [PATCH 03/25] crypto: pem_decode_from_bytes gives an array of bytes, whose type every target prints alike --- doc/generated/messages.adoc | 2 +- .../pem_decode_from_bytes/pem_decode_from_bytes.cpp | 10 +++++----- test/msvc/pem_decode_from_bytes/app.cpp | 5 ++--- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 26379108..9985f5bf 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -595,7 +595,7 @@ The fix: Leave the backend out, as in `+curves::p256::keypair+`, or name `+backe |`+pem_decode_from_bytes+` |native, wasip2, wasip3 -|`+static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char+` +|`+static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char+` The fix: Give a PEM to `+crypto::decode+` or `+codecs::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. diff --git a/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp b/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp index 126ab897..bf6b8cd6 100644 --- a/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp +++ b/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp @@ -6,12 +6,13 @@ // crypto::decode of a PEM pair of crypto's from bytes, not a text, stops in codecs' typed decode, // where the PEM's value codec, codecs' over, decodes from text (codecs' ruling R25), and with that -// error alone; its requirement names the input's type and the PEM's. +// error alone; its requirement names the input's type, an array of bytes (whose type every target +// prints alike), and the PEM's. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char}} +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char}} // clang-format on #include "../../support/formats_toy.hpp" @@ -20,12 +21,11 @@ #include #include -#include int main() { namespace crypto = webcpp::crypto; std::array const bytes{}; - auto const decoded = crypto::decode( - crypto::formats::pem(crypto::formats::spki), std::span(bytes)); + auto const decoded = + crypto::decode(crypto::formats::pem(crypto::formats::spki), bytes); return decoded ? 0 : 1; } diff --git a/test/msvc/pem_decode_from_bytes/app.cpp b/test/msvc/pem_decode_from_bytes/app.cpp index cf9148f6..1cb65059 100644 --- a/test/msvc/pem_decode_from_bytes/app.cpp +++ b/test/msvc/pem_decode_from_bytes/app.cpp @@ -12,12 +12,11 @@ #include #include -#include int main() { namespace crypto = webcpp::crypto; std::array const bytes{}; - auto const decoded = crypto::decode( - crypto::formats::pem(crypto::formats::spki), std::span(bytes)); + auto const decoded = + crypto::decode(crypto::formats::pem(crypto::formats::spki), bytes); return decoded ? 0 : 1; } From e00b5523c297c43c50722f2b5addafd3824e8699 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 23:04:10 -0300 Subject: [PATCH 04/25] crypto: the fuzz check of no intermediate past the bound counts the armor's own state's wipes, a payload of its size in the corpus --- test/fuzz/Jamfile | 6 ++- .../corpus/ed25519_pem_pkcs8/past_bound_84 | 4 ++ .../corpus/x25519_pem_pkcs8/past_bound_84 | 4 ++ test/fuzz/target.hpp | 47 +++++++++++++++++-- 4 files changed, 54 insertions(+), 7 deletions(-) create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/past_bound_84 create mode 100644 test/fuzz/corpus/x25519_pem_pkcs8/past_bound_84 diff --git a/test/fuzz/Jamfile b/test/fuzz/Jamfile index 180ee25c..53078a92 100644 --- a/test/fuzz/Jamfile +++ b/test/fuzz/Jamfile @@ -91,7 +91,8 @@ crypto-fuzz base58_with_checksum : /webcpp/hash//base58_with_checksum ; # bytes, a key pair's seed and a signature's 64 bytes, one target for the # three; spki; pkcs8, its version 2 (30 51, 83 bytes, and RFC 8410's with an # attribute) among them; pem(spki) and pem(pkcs8), with CRLF lines, without the -# final line feed and with explanatory text before BEGIN. +# final line feed and with explanatory text before BEGIN, and pem(pkcs8) of 84 +# zero bytes, past the bound and the size of the armor's own wiped state. crypto-fuzz ed25519_raw : /third_party//sodium ; crypto-fuzz ed25519_spki : /third_party//sodium ; crypto-fuzz ed25519_pkcs8 : /third_party//sodium ; @@ -105,7 +106,8 @@ crypto-fuzz ed25519_pem_pkcs8 : /third_party//sodium ; # public key's 32 bytes and a key pair's secret key, one target for the two; # spki; pkcs8, its version 2 (30 51, 83 bytes) among them; pem(spki) and # pem(pkcs8), with CRLF lines, without the final line feed and with -# explanatory text before BEGIN. +# explanatory text before BEGIN, and pem(pkcs8) of 84 zero bytes, past the +# bound and the size of the armor's own wiped state. crypto-fuzz x25519_raw : /third_party//sodium ; crypto-fuzz x25519_spki : /third_party//sodium ; crypto-fuzz x25519_pkcs8 : /third_party//sodium ; diff --git a/test/fuzz/corpus/ed25519_pem_pkcs8/past_bound_84 b/test/fuzz/corpus/ed25519_pem_pkcs8/past_bound_84 new file mode 100644 index 00000000..f87bf076 --- /dev/null +++ b/test/fuzz/corpus/ed25519_pem_pkcs8/past_bound_84 @@ -0,0 +1,4 @@ +-----BEGIN PRIVATE KEY----- +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +-----END PRIVATE KEY----- diff --git a/test/fuzz/corpus/x25519_pem_pkcs8/past_bound_84 b/test/fuzz/corpus/x25519_pem_pkcs8/past_bound_84 new file mode 100644 index 00000000..f87bf076 --- /dev/null +++ b/test/fuzz/corpus/x25519_pem_pkcs8/past_bound_84 @@ -0,0 +1,4 @@ +-----BEGIN PRIVATE KEY----- +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +-----END PRIVATE KEY----- diff --git a/test/fuzz/target.hpp b/test/fuzz/target.hpp index d93d5f36..556b7231 100644 --- a/test/fuzz/target.hpp +++ b/test/fuzz/target.hpp @@ -42,7 +42,9 @@ #include #include #include +#include #include +#include /** The fuzz target, libFuzzer's entry point, which each `_fuzz.cpp` defines and the replay @@ -179,17 +181,37 @@ inline void expect_wiped(std::size_t required_size, char const* what) noexcept { /** Checks secure's wipe record after a secret PEM's decode refused for a payload past its bound: - every wipe left only zero bytes and was kept, and none was of the payload's size, so no - intermediate held it. + every wipe left only zero bytes and was kept, and the wipes of the payload's size are those of + the same decode of a reference text past the bound, the armor's own state (a fixed size, which + a payload's may equal), so no intermediate held the payload. @param payload_size The payload's size. + @param reference_count The wipes of that size the reference decode made. @param what The call, for the message. */ -inline void expect_no_intermediate(std::size_t payload_size, char const* what) noexcept { +inline void expect_no_intermediate(std::size_t payload_size, std::size_t reference_count, + char const* what) noexcept { fuzz_wipe_summary const wipes = fuzz_wipes(payload_size); expect(wipes.all_kept, what); expect(wipes.not_zero == 0, what); - expect(wipes.of_size == 0, what); + expect(wipes.of_size == reference_count, what); +} + +/** + A PEM text of `Inner` whose payload is `size` zero bytes, made once for each size asked (onto the + heap: called outside the counted region). + + @tparam Inner The PEM's inner format. + @param size The payload's size. + @return The text. +*/ +template +std::string pem_text_of_size(std::size_t size) { + std::vector const payload(size); + auto const text = codecs::encode(codecs::formats::armor(crypto::detail::pem_label_v), + payload, codecs::tokens::return_string); + expect(text.has_value(), "the reference text does not encode"); + return text ? *text : std::string{}; } /** @@ -250,10 +272,25 @@ void fuzz_decode(Format format, std::span input) { constexpr std::size_t bound = formats::max_decode_input_size; bool const past_bound = payload_size.has_value() && *payload_size > bound; std::size_t const intermediate_size = payload_size && !past_bound ? *payload_size : 0; + std::size_t reference_count = 0; if constexpr (secret) { // The wipes since the last check, the previous input's values' and the payload's read // among them: every one left zero bytes. expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); + if constexpr (parts::pem) { + if (past_bound) { + // The wipes of the payload's size that a decode past the bound makes with no + // intermediate: a reference text's, one byte past the bound. + static std::string const reference = + fuzz_detail::pem_text_of_size(bound + 1); + auto const refused = crypto::decode(format, std::string_view{reference}); + expect(!refused && refused.error() == codecs::error::input_too_long, + "the reference text past the bound is not input_too_long"); + fuzz_wipe_summary const wipes = fuzz_wipes(*payload_size); + expect(wipes.not_zero == 0, "a wipe left a byte not zero"); + reference_count = wipes.of_size; + } + } } std::size_t const before = fuzz_allocations(); @@ -271,7 +308,7 @@ void fuzz_decode(Format format, std::span input) { "an input past the bound is not input_too_long"); if constexpr (secret) { if (past_bound) { - fuzz_detail::expect_no_intermediate(*payload_size, + fuzz_detail::expect_no_intermediate(*payload_size, reference_count, "the decode made an intermediate past the bound"); } else { fuzz_detail::expect_wiped(intermediate_size, "the decode left a buffer not wiped"); From 3d6bbf6226d1defd889728fdece14e34492fb25b Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 23:27:08 -0300 Subject: [PATCH 05/25] crypto: the fuzz decode check's reference wipes in a helper (lint fix) --- test/fuzz/target.hpp | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/test/fuzz/target.hpp b/test/fuzz/target.hpp index 556b7231..cf22678c 100644 --- a/test/fuzz/target.hpp +++ b/test/fuzz/target.hpp @@ -214,6 +214,30 @@ std::string pem_text_of_size(std::size_t size) { return text ? *text : std::string{}; } +/** + The wipes of `payload_size` bytes that a secret PEM's decode of a reference text, whose payload + is `reference_size` bytes past the bound, makes: the armor's own state's, with no intermediate. + + @tparam Value The value's type. + @tparam Format The PEM format's type. + @param format The format. + @param reference_size The reference payload's size, past the bound. + @param payload_size The size of the wipes to count. + @return How many wipes of that size the reference decode made. +*/ +template +std::size_t reference_wipes(Format const& format, std::size_t reference_size, + std::size_t payload_size) { + using inner = format_parts::inner; + static std::string const reference = pem_text_of_size(reference_size); + auto const refused = crypto::decode(format, std::string_view{reference}); + expect(!refused && refused.error() == codecs::error::input_too_long, + "the reference text past the bound is not input_too_long"); + fuzz_wipe_summary const wipes = fuzz_wipes(payload_size); + expect(wipes.not_zero == 0, "a wipe left a byte not zero"); + return wipes.of_size; +} + /** Whether the value codec of `Format` and `Value` is secret: it states `secret`, and it is true. @@ -279,16 +303,8 @@ void fuzz_decode(Format format, std::span input) { expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); if constexpr (parts::pem) { if (past_bound) { - // The wipes of the payload's size that a decode past the bound makes with no - // intermediate: a reference text's, one byte past the bound. - static std::string const reference = - fuzz_detail::pem_text_of_size(bound + 1); - auto const refused = crypto::decode(format, std::string_view{reference}); - expect(!refused && refused.error() == codecs::error::input_too_long, - "the reference text past the bound is not input_too_long"); - fuzz_wipe_summary const wipes = fuzz_wipes(*payload_size); - expect(wipes.not_zero == 0, "a wipe left a byte not zero"); - reference_count = wipes.of_size; + reference_count = + fuzz_detail::reference_wipes(format, bound + 1, *payload_size); } } } From 0af4260a01ebefec1506912d37a8205f54d48dd0 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 23:45:17 -0300 Subject: [PATCH 06/25] crypto: the fuzz decode check's reference count const (lint fix) --- test/fuzz/target.hpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/test/fuzz/target.hpp b/test/fuzz/target.hpp index cf22678c..485132e6 100644 --- a/test/fuzz/target.hpp +++ b/test/fuzz/target.hpp @@ -296,18 +296,22 @@ void fuzz_decode(Format format, std::span input) { constexpr std::size_t bound = formats::max_decode_input_size; bool const past_bound = payload_size.has_value() && *payload_size > bound; std::size_t const intermediate_size = payload_size && !past_bound ? *payload_size : 0; - std::size_t reference_count = 0; if constexpr (secret) { // The wipes since the last check, the previous input's values' and the payload's read // among them: every one left zero bytes. expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); - if constexpr (parts::pem) { - if (past_bound) { - reference_count = - fuzz_detail::reference_wipes(format, bound + 1, *payload_size); - } - } } + // A secret PEM past the bound: the wipes of the payload's size its decode makes with no + // intermediate, read before the counted region. + std::size_t const reference_count = [&]() -> std::size_t { + if constexpr (secret && parts::pem) { + return past_bound + ? fuzz_detail::reference_wipes(format, bound + 1, *payload_size) + : 0; + } else { + return 0; + } + }(); std::size_t const before = fuzz_allocations(); auto const decoded = [&] { From a893a9a5dbefb8421cbda522b3822439be531086 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 2 Dec 2026 23:58:43 -0300 Subject: [PATCH 07/25] crypto: the fuzz decode check's wipes in helpers, its complexity under the limit (lint fix) --- test/fuzz/target.hpp | 74 ++++++++++++++++++++++++++++++-------------- 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/test/fuzz/target.hpp b/test/fuzz/target.hpp index 485132e6..2946b4f3 100644 --- a/test/fuzz/target.hpp +++ b/test/fuzz/target.hpp @@ -238,6 +238,53 @@ std::size_t reference_wipes(Format const& format, std::size_t reference_size, return wipes.of_size; } +/** + Reads secure's wipe record before a decode, `Secret`'s alone: every wipe since the last check + (the previous input's values', the payload's read) left zero bytes; then, for a PEM whose payload + is past the bound, the wipes of the payload's size that a reference text past the bound makes. + + @tparam Value The value's type. + @tparam Secret Whether the decode is secret. + @tparam Format The format's type. + @param format The format. + @param payload_size The PEM's payload's size, none when the armor refuses the text or for + another format. + @return The reference's wipes of the payload's size; 0 when none is read. +*/ +template +std::size_t wipes_before_decode(Format const& format, std::optional payload_size) { + if constexpr (Secret) { + expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); + if constexpr (format_parts::pem) { + constexpr std::size_t bound = + formats::max_decode_input_size::inner, Value>; + if (payload_size && *payload_size > bound) { + return reference_wipes(format, bound + 1, *payload_size); + } + } + } + return 0; +} + +/** + Checks secure's wipe record after a secret decode: a PEM's intermediate, the payload's bytes, wiped + when the payload is within the bound, none made past it; every wipe leaving zero bytes. + + @param payload_size The PEM's payload's size, none when the armor refuses the text or for + another format. + @param bound The inner format's decode bound. + @param reference_count The reference's wipes of the payload's size. +*/ +inline void expect_decode_wipes(std::optional payload_size, std::size_t bound, + std::size_t reference_count) noexcept { + if (payload_size && *payload_size > bound) { + expect_no_intermediate(*payload_size, reference_count, + "the decode made an intermediate past the bound"); + } else { + expect_wiped(payload_size.value_or(0), "the decode left a buffer not wiped"); + } +} + /** Whether the value codec of `Format` and `Value` is secret: it states `secret`, and it is true. @@ -295,23 +342,9 @@ void fuzz_decode(Format format, std::span input) { } constexpr std::size_t bound = formats::max_decode_input_size; bool const past_bound = payload_size.has_value() && *payload_size > bound; - std::size_t const intermediate_size = payload_size && !past_bound ? *payload_size : 0; - if constexpr (secret) { - // The wipes since the last check, the previous input's values' and the payload's read - // among them: every one left zero bytes. - expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); - } - // A secret PEM past the bound: the wipes of the payload's size its decode makes with no - // intermediate, read before the counted region. - std::size_t const reference_count = [&]() -> std::size_t { - if constexpr (secret && parts::pem) { - return past_bound - ? fuzz_detail::reference_wipes(format, bound + 1, *payload_size) - : 0; - } else { - return 0; - } - }(); + // The wipes before the decode, and those a decode past the bound makes with no intermediate. + std::size_t const reference_count = + fuzz_detail::wipes_before_decode(format, payload_size); std::size_t const before = fuzz_allocations(); auto const decoded = [&] { @@ -327,12 +360,7 @@ void fuzz_decode(Format format, std::span input) { expect(!input_past_bound || (!decoded && decoded.error() == codecs::error::input_too_long), "an input past the bound is not input_too_long"); if constexpr (secret) { - if (past_bound) { - fuzz_detail::expect_no_intermediate(*payload_size, reference_count, - "the decode made an intermediate past the bound"); - } else { - fuzz_detail::expect_wiped(intermediate_size, "the decode left a buffer not wiped"); - } + fuzz_detail::expect_decode_wipes(payload_size, bound, reference_count); } if (!decoded) { return; From f49337b5828d302d036c259543366b3f30ba4902 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 3 Dec 2026 00:24:02 -0300 Subject: [PATCH 08/25] crypto: the PEM fuzz wipe check and the X25519 past-bound count completed --- test/formats_x25519_sodium_test.cpp | 8 ++ test/fuzz/Jamfile | 11 ++- .../corpus/p256_pem_pkcs8/within_bound_84 | 4 + .../secp256k1_pem_pkcs8/within_bound_84 | 4 + test/fuzz/target.hpp | 73 ++++++++++++------- 5 files changed, 70 insertions(+), 30 deletions(-) create mode 100644 test/fuzz/corpus/p256_pem_pkcs8/within_bound_84 create mode 100644 test/fuzz/corpus/secp256k1_pem_pkcs8/within_bound_84 diff --git a/test/formats_x25519_sodium_test.cpp b/test/formats_x25519_sodium_test.cpp index 0e39eed3..fd10cd00 100644 --- a/test/formats_x25519_sodium_test.cpp +++ b/test/formats_x25519_sodium_test.cpp @@ -314,6 +314,8 @@ struct case_counts { std::size_t acceptable = 0; /** The cases marked invalid. */ std::size_t invalid = 0; + /** The invalid cases with a key longer than its pair's decode bound. */ + std::size_t past_bound = 0; }; /** @@ -380,6 +382,10 @@ bool check_case(json::value const& test_case, Input const& public_input, Input c auto const private_expected = crypto::test::expected_error( der_size(private_input, "PRIVATE KEY"), crypto::error::invalid_encoding); + if (public_expected == codecs::error::input_too_long || + private_expected == codecs::error::input_too_long) { + ++counts.past_bound; + } return (!public_key || !key_pair) && (public_key || public_key.error() == public_expected) && (key_pair || key_pair.error() == private_expected); @@ -425,6 +431,8 @@ void wycheproof_asn() { BOOST_TEST_EQ(counts.valid, 265U); BOOST_TEST_EQ(counts.acceptable, 253U); BOOST_TEST_EQ(counts.invalid, 19U); + // The input_too_long branch is taken: some invalid case is past its pair's bound. + BOOST_TEST_GT(counts.past_bound, 0U); } /** diff --git a/test/fuzz/Jamfile b/test/fuzz/Jamfile index 53078a92..e81605fe 100644 --- a/test/fuzz/Jamfile +++ b/test/fuzz/Jamfile @@ -125,7 +125,8 @@ crypto-fuzz x25519_pem_pkcs8 : /third_party//sodium ; # forms; pkcs8, the 150 bytes with [0] parameters and the 67 without the public # key among them; der, a signature's strict DER and its raw 64 bytes; pem(spki) # and pem(pkcs8), with CRLF lines, without the final line feed and with -# explanatory text before BEGIN, an RSA key's PEM among them. +# explanatory text before BEGIN, an RSA key's PEM among them, and pem(pkcs8) of +# 84 zero bytes, within the bound and the size of the armor's own wiped state. crypto-fuzz p256_raw : /third_party//bearssl ; crypto-fuzz p256_spki : /third_party//bearssl ; crypto-fuzz p256_pkcs8 : /third_party//bearssl ; @@ -144,9 +145,11 @@ crypto-fuzz p256_pem_pkcs8 : /third_party//bearssl ; # the one without it and [0] parameters among them; der, a signature's strict # DER and the three signatures' raw; pem(spki) and pem(pkcs8), with CRLF # lines, without the final line feed and with explanatory text before BEGIN, -# an RSA key's PEM among them. A key pair's signing context comes from the -# default memory resource, which the key pair targets set to blocks of their -# own (secp256k1_resource.hpp), so that nothing is on the heap. +# an RSA key's PEM among them, and pem(pkcs8) of 84 zero bytes, within the +# bound and the size of the armor's own wiped state. A key pair's signing +# context comes from the default memory resource, which the key pair targets +# set to blocks of their own (secp256k1_resource.hpp), so that nothing is on +# the heap. crypto-fuzz secp256k1_raw : /third_party//secp256k1 ; crypto-fuzz secp256k1_xonly_raw : /third_party//secp256k1 ; crypto-fuzz secp256k1_spki : /third_party//secp256k1 ; diff --git a/test/fuzz/corpus/p256_pem_pkcs8/within_bound_84 b/test/fuzz/corpus/p256_pem_pkcs8/within_bound_84 new file mode 100644 index 00000000..f87bf076 --- /dev/null +++ b/test/fuzz/corpus/p256_pem_pkcs8/within_bound_84 @@ -0,0 +1,4 @@ +-----BEGIN PRIVATE KEY----- +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +-----END PRIVATE KEY----- diff --git a/test/fuzz/corpus/secp256k1_pem_pkcs8/within_bound_84 b/test/fuzz/corpus/secp256k1_pem_pkcs8/within_bound_84 new file mode 100644 index 00000000..f87bf076 --- /dev/null +++ b/test/fuzz/corpus/secp256k1_pem_pkcs8/within_bound_84 @@ -0,0 +1,4 @@ +-----BEGIN PRIVATE KEY----- +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +-----END PRIVATE KEY----- diff --git a/test/fuzz/target.hpp b/test/fuzz/target.hpp index 2946b4f3..20f5eca1 100644 --- a/test/fuzz/target.hpp +++ b/test/fuzz/target.hpp @@ -166,17 +166,32 @@ struct format_parts> { }; /** - Checks secure's wipe record after a secret call: every wipe left only zero bytes and was kept, - and, after a PEM's decode, its intermediate of `required_size` bytes was wiped. + Checks secure's wipe record after a secret call: every wipe left only zero bytes and was kept. - @param required_size The size of the wipe that must be found, or 0 for none. @param what The call, for the message. */ -inline void expect_wiped(std::size_t required_size, char const* what) noexcept { - fuzz_wipe_summary const wipes = fuzz_wipes(required_size); +inline void expect_wiped(char const* what) noexcept { + fuzz_wipe_summary const wipes = fuzz_wipes(0); expect(wipes.all_kept, what); expect(wipes.not_zero == 0, what); - expect(required_size == 0 || wipes.of_size != 0, what); +} + +/** + Checks secure's wipe record after a secret PEM's decode whose payload is within its bound: every + wipe left only zero bytes and was kept, and the wipes of the payload's size are those of the same + decode of a reference text of another size within the bound, the armor's own state (a fixed size, + which a payload's may equal), and one more, the intermediate that held the payload. + + @param payload_size The payload's size. + @param reference_count The wipes of that size the reference decode made. + @param what The call, for the message. +*/ +inline void expect_intermediate_wiped(std::size_t payload_size, std::size_t reference_count, + char const* what) noexcept { + fuzz_wipe_summary const wipes = fuzz_wipes(payload_size); + expect(wipes.all_kept, what); + expect(wipes.not_zero == 0, what); + expect(wipes.of_size == reference_count + 1, what); } /** @@ -198,8 +213,8 @@ inline void expect_no_intermediate(std::size_t payload_size, std::size_t referen } /** - A PEM text of `Inner` whose payload is `size` zero bytes, made once for each size asked (onto the - heap: called outside the counted region). + A PEM text of `Inner` whose payload is `size` zero bytes (onto the heap: called outside the counted + region). @tparam Inner The PEM's inner format. @param size The payload's size. @@ -215,24 +230,28 @@ std::string pem_text_of_size(std::size_t size) { } /** - The wipes of `payload_size` bytes that a secret PEM's decode of a reference text, whose payload - is `reference_size` bytes past the bound, makes: the armor's own state's, with no intermediate. + The wipes of `payload_size` bytes that a secret PEM's decode of a reference text makes beside an + intermediate of the payload: for a payload past the bound, a text one byte past it, which makes + no intermediate; for one within it, a text of another size within it, whose intermediate is of + its own size. Either counts the armor's own state's wipes of that size alone. @tparam Value The value's type. @tparam Format The PEM format's type. @param format The format. - @param reference_size The reference payload's size, past the bound. - @param payload_size The size of the wipes to count. + @param payload_size The size of the wipes to count, the payload's, more than 0. @return How many wipes of that size the reference decode made. */ template -std::size_t reference_wipes(Format const& format, std::size_t reference_size, - std::size_t payload_size) { +std::size_t reference_wipes(Format const& format, std::size_t payload_size) { using inner = format_parts::inner; - static std::string const reference = pem_text_of_size(reference_size); + constexpr std::size_t bound = formats::max_decode_input_size; + bool const past_bound = payload_size > bound; + std::size_t const other_within = payload_size > 1 ? payload_size - 1 : 2; + // Zero bytes are no DER of a key: every reference decode is refused. + std::string const reference = pem_text_of_size(past_bound ? bound + 1 : other_within); auto const refused = crypto::decode(format, std::string_view{reference}); - expect(!refused && refused.error() == codecs::error::input_too_long, - "the reference text past the bound is not input_too_long"); + expect(!refused && (!past_bound || refused.error() == codecs::error::input_too_long), + "the reference text decodes, or past the bound is not input_too_long"); fuzz_wipe_summary const wipes = fuzz_wipes(payload_size); expect(wipes.not_zero == 0, "a wipe left a byte not zero"); return wipes.of_size; @@ -240,8 +259,9 @@ std::size_t reference_wipes(Format const& format, std::size_t reference_size, /** Reads secure's wipe record before a decode, `Secret`'s alone: every wipe since the last check - (the previous input's values', the payload's read) left zero bytes; then, for a PEM whose payload - is past the bound, the wipes of the payload's size that a reference text past the bound makes. + (the previous input's values', the payload's read) left zero bytes; then, for a PEM whose armor + reads the text, the wipes of the payload's size that a reference text makes beside an + intermediate of the payload (`reference_wipes`). @tparam Value The value's type. @tparam Secret Whether the decode is secret. @@ -256,10 +276,8 @@ std::size_t wipes_before_decode(Format const& format, std::optional if constexpr (Secret) { expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); if constexpr (format_parts::pem) { - constexpr std::size_t bound = - formats::max_decode_input_size::inner, Value>; - if (payload_size && *payload_size > bound) { - return reference_wipes(format, bound + 1, *payload_size); + if (payload_size && *payload_size != 0) { + return reference_wipes(format, *payload_size); } } } @@ -268,7 +286,7 @@ std::size_t wipes_before_decode(Format const& format, std::optional /** Checks secure's wipe record after a secret decode: a PEM's intermediate, the payload's bytes, wiped - when the payload is within the bound, none made past it; every wipe leaving zero bytes. + once when the payload is within the bound, none made past it; every wipe leaving zero bytes. @param payload_size The PEM's payload's size, none when the armor refuses the text or for another format. @@ -280,8 +298,11 @@ inline void expect_decode_wipes(std::optional payload_size, std::si if (payload_size && *payload_size > bound) { expect_no_intermediate(*payload_size, reference_count, "the decode made an intermediate past the bound"); + } else if (payload_size && *payload_size != 0) { + expect_intermediate_wiped(*payload_size, reference_count, + "the decode left its intermediate not wiped"); } else { - expect_wiped(payload_size.value_or(0), "the decode left a buffer not wiped"); + expect_wiped("the decode left a buffer not wiped"); } } @@ -378,7 +399,7 @@ void fuzz_decode(Format format, std::span input) { "what decoded encodes to other bytes than the input"); } if constexpr (secret) { - fuzz_detail::expect_wiped(0, "the encode left a buffer not wiped"); + fuzz_detail::expect_wiped("the encode left a buffer not wiped"); } } From 1e38f393393c87def3e3b21aa3b302a34f70c8d7 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 3 Dec 2026 00:44:28 -0300 Subject: [PATCH 09/25] crypto: crypto's types are declared to codecs, with D3's sentences; PEM's label is in its type; the members call codecs' verbs --- doc/generated/messages.adoc | 58 ++- doc/llms.txt | 12 +- doc/tables/crypto.json | 10 +- doc/tables/generate.py | 4 +- doc/tables/generate_test.py | 8 +- .../webcpp/crypto/curves/ed25519/formats.hpp | 43 +- include/webcpp/crypto/curves/p256/formats.hpp | 41 +- .../crypto/curves/secp256k1/formats.hpp | 81 ++-- .../webcpp/crypto/curves/x25519/formats.hpp | 41 +- .../webcpp/crypto/detail/format_members.hpp | 16 +- include/webcpp/crypto/detail/signature.hpp | 8 +- include/webcpp/crypto/formats.hpp | 453 +++++++++--------- test/Jamfile | 19 +- test/formats_asynchronous_test.cpp | 14 +- test/formats_before_after_test.cpp | 25 +- test/formats_ed25519_sodium_test.cpp | 29 +- test/formats_pem_test.cpp | 51 +- test/formats_stand_in_test.cpp | 63 ++- test/formats_table_test.cpp | 158 +++++- test/formats_verbs_test.cpp | 188 ++++++-- test/formats_vocabulary_test.cpp | 60 ++- test/formats_x25519_sodium_test.cpp | 29 +- test/fuzz/target.hpp | 7 +- test/messages/Jamfile | 4 + .../decode_refusal_reason_toy.cpp | 6 +- .../der_on_ed25519/der_on_ed25519.cpp | 6 +- .../der_on_recoverable/der_on_recoverable.cpp | 6 +- .../der_on_schnorr/der_on_schnorr.cpp | 6 +- .../ed25519_formats_header_missing.cpp | 8 +- test/messages/foreign_format_on_key/Jamfile | 14 + .../foreign_format_on_key.cpp | 32 ++ .../format_header_missing_toy.cpp | 12 +- .../format_refused_toy/format_refused_toy.cpp | 15 +- .../forms_without_default.cpp | 6 +- .../keypair_decode_resource_spki.cpp | 8 +- test/messages/member_der_on_ed25519/Jamfile | 14 + .../member_der_on_ed25519.cpp | 25 + .../pem_decode_from_bytes.cpp | 8 +- test/messages/pem_other_armor/Jamfile | 14 + .../pem_other_armor/pem_other_armor.cpp | 35 ++ test/messages/pem_other_basic_armor/Jamfile | 14 + .../pem_other_basic_armor.cpp | 35 ++ .../pkcs8_on_asynchronous_ed25519.cpp | 10 +- .../pkcs8_on_asynchronous_p256.cpp | 10 +- .../raw_on_asynchronous_x25519.cpp | 8 +- .../refusal_reason_toy/refusal_reason_toy.cpp | 6 +- .../x25519_formats_header_missing.cpp | 8 +- .../xonly_into_public_key.cpp | 6 +- test/msvc/Jamfile | 4 + test/msvc/decode_refusal_reason_toy/app.cpp | 4 +- test/msvc/der_on_ed25519/app.cpp | 4 +- test/msvc/der_on_recoverable/app.cpp | 4 +- test/msvc/der_on_schnorr/app.cpp | 4 +- .../ed25519_formats_header_missing/app.cpp | 4 +- test/msvc/foreign_format_on_key/Jamfile | 10 + test/msvc/foreign_format_on_key/app.cpp | 24 + test/msvc/format_header_missing_toy/app.cpp | 4 +- test/msvc/format_refused_toy/app.cpp | 6 +- test/msvc/forms_without_default/app.cpp | 4 +- test/msvc/member_der_on_ed25519/Jamfile | 10 + test/msvc/member_der_on_ed25519/app.cpp | 18 + test/msvc/pem_decode_from_bytes/app.cpp | 4 +- test/msvc/pem_other_armor/Jamfile | 10 + test/msvc/pem_other_armor/app.cpp | 27 ++ test/msvc/pem_other_basic_armor/Jamfile | 10 + test/msvc/pem_other_basic_armor/app.cpp | 27 ++ .../pkcs8_on_asynchronous_ed25519/app.cpp | 4 +- test/msvc/pkcs8_on_asynchronous_p256/app.cpp | 4 +- test/msvc/raw_on_asynchronous_x25519/app.cpp | 4 +- test/msvc/refusal_reason_toy/app.cpp | 4 +- .../x25519_formats_header_missing/app.cpp | 4 +- test/msvc/xonly_into_public_key/app.cpp | 4 +- test/p256_formats_bearssl_test.cpp | 50 +- test/secp256k1_formats_test.cpp | 68 +-- test/support/format_checks.hpp | 58 +-- test/support/formats_toy.hpp | 97 ++-- 76 files changed, 1489 insertions(+), 720 deletions(-) create mode 100644 test/messages/foreign_format_on_key/Jamfile create mode 100644 test/messages/foreign_format_on_key/foreign_format_on_key.cpp create mode 100644 test/messages/member_der_on_ed25519/Jamfile create mode 100644 test/messages/member_der_on_ed25519/member_der_on_ed25519.cpp create mode 100644 test/messages/pem_other_armor/Jamfile create mode 100644 test/messages/pem_other_armor/pem_other_armor.cpp create mode 100644 test/messages/pem_other_basic_armor/Jamfile create mode 100644 test/messages/pem_other_basic_armor/pem_other_basic_armor.cpp create mode 100644 test/msvc/foreign_format_on_key/Jamfile create mode 100644 test/msvc/foreign_format_on_key/app.cpp create mode 100644 test/msvc/member_der_on_ed25519/Jamfile create mode 100644 test/msvc/member_der_on_ed25519/app.cpp create mode 100644 test/msvc/pem_other_armor/Jamfile create mode 100644 test/msvc/pem_other_armor/app.cpp create mode 100644 test/msvc/pem_other_basic_armor/Jamfile create mode 100644 test/msvc/pem_other_basic_armor/app.cpp diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 9985f5bf..f2eb625f 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -409,6 +409,12 @@ The fix: Call `+webcpp::secure::constant_time_equal+`, the same comparison of tw The fix: Call `+webcpp::secure::erase_secret+`, from `++`, the same erasure; `+crypto::erase_secret+` moved to webcpp::secure, with no alias. +|`+foreign_format_on_key+` +|native, wasip2, wasip3 +|`+webcpp::codecs::detail::format_listed, webcpp::crypto::formats::spki_t, webcpp::codecs::over>>, webcpp::crypto::formats::spki_t, std::allocator>>>': webcpp::codecs: this type has no such format; the formats it has are the format_list named in this assertion+` + +The fix: Encode or decode a key in one of the formats of its list, the `+codecs::format_list+` the assertion names; for its bytes in hexadecimal, compose a format of its list, `+codecs::over{codecs::formats::hex, crypto::formats::raw}+`. + |`+format_header_missing_toy+` |native, wasip2, wasip3 |`+webcpp::crypto: include to encode or decode this type+` @@ -417,9 +423,9 @@ The fix: Include the formats header of the type's curve, the one the assertion n |`+format_refused_toy+` |native, wasip2, wasip3 -|`+webcpp::crypto::detail::format_list, webcpp::crypto::formats::spki_t, webcpp::codecs::over, std::allocator>>>': webcpp::crypto: this type has no such format; the formats it has are the format_list named in this assertion+` +|`+webcpp::codecs::format_list, webcpp::crypto::formats::spki_t, webcpp::codecs::over>>, webcpp::crypto::formats::spki_t, std::allocator>>>': webcpp::codecs: this type has no such format; the formats it has are the format_list named in this assertion+` -The fix: Encode or decode a type in a format of its list, the `+format_list+` the assertion names: another type's format (`+der+` is an ECDSA signature's, `+pkcs8+` a key pair's) does not convert it. +The fix: Encode or decode a type in a format of its list, the `+codecs::format_list+` the assertion names: another type's format (`+der+` is an ECDSA signature's, `+pkcs8+` a key pair's) does not convert it. |`+format_without_header+` |native, wasip2, wasip3 @@ -487,7 +493,7 @@ The fix: Give the key pair's decode with a memory resource bytes for `+crypto::f |`+keypair_decode_resource_spki+` |native, wasip2, wasip3 -|`+webcpp::crypto: this type has no such format; the formats it has are the format_list named in this assertion+` +|`+webcpp::codecs::format_list, webcpp::crypto::formats::pkcs8_t, webcpp::codecs::over>, webcpp::crypto::formats::pkcs8_t, std::allocator>>>': webcpp::codecs: this type has no such format; the formats it has are the format_list named in this assertion+` The fix: Decode a secp256k1 key pair, with or without a memory resource, from one of its formats: `+crypto::formats::raw+`, its secret key, `+crypto::formats::pkcs8+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`; an SPKI holds a public key, which `+crypto::curves::secp256k1::public_key::decode(crypto::formats::spki, bytes)+` gives. @@ -515,6 +521,12 @@ The fix: Only an ECDSA signature has low S: Ed25519 and Schnorr signatures have The fix: Call the factory named by its input, member or free: `+from_secret+` for a key pair, `+from_bytes+` for a public key, `+from_key+` for a cipher (`+crypto::from_secret(bytes)+`, `+K::from_secret(bytes)+`); `+make+` is gone, with no alias. +|`+member_der_on_ed25519+` +|native, wasip2, wasip3 +|`+webcpp::crypto: Ed25519 and BIP340 signatures have no DER form; their 64 bytes are the signature+` + +The fix: As `+der_on_ed25519+`: encode an Ed25519 signature with `+signature.encode(crypto::formats::raw)+`, or `+codecs::encode(crypto::formats::raw, signature)+`: its 64 bytes are the signature, and it has no DER form. + |`+musig_nonce_copied+` |native, wasip2 |`+call to deleted constructor of+` @@ -595,9 +607,9 @@ The fix: Leave the backend out, as in `+curves::p256::keypair+`, or name `+backe |`+pem_decode_from_bytes+` |native, wasip2, wasip3 -|`+static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char+` +|`+static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over>>, webcpp::crypto::formats::spki_t, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char+` -The fix: Give a PEM to `+crypto::decode+` or `+codecs::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. +The fix: Give a PEM to `+codecs::decode+`, or a type's member `+decode+`, as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. |`+pem_header_removed+` |native, wasip2, wasip3 @@ -623,6 +635,18 @@ The fix: Armor the DER of a key: `+crypto::formats::pem(crypto::formats::spki)+` The fix: As `+pem_of_der+`: armor the DER of a key, `+crypto::formats::pem(crypto::formats::spki)+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`; a key's raw bytes have no PEM. +|`+pem_other_armor+` +|native, wasip2, wasip3 +|`+webcpp::crypto: a key's PEM is formats::pem(formats::spki) or formats::pem(formats::pkcs8), whose label is the inner format's+` + +The fix: Encode or decode a key's PEM with `+crypto::formats::pem(crypto::formats::spki)+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`, whose label, `+PUBLIC KEY+` or `+PRIVATE KEY+`, is in its type; a text under another label, a certificate's among them, is no key, and decoding it gives `+codecs::error::invalid_prefix+`. + +|`+pem_other_basic_armor+` +|native, wasip2, wasip3 +|`+webcpp::crypto: a key's PEM is formats::pem(formats::spki) or formats::pem(formats::pkcs8), whose label is the inner format's+` + +The fix: As `+pem_other_armor+`: name a key's PEM by `+crypto::formats::pem(F)+`, never by `+codecs::formats::basic_armor+` of a label, so that the label is always the inner format's. + |`+ph_removed+` |native, wasip2, wasip3 |`+no member named 'ph' in namespace+` @@ -1153,7 +1177,7 @@ The fix: Make the x-only key with a value: `+curves::secp256k1::xonly_public_key |native, wasip2, wasip3 |`+webcpp::crypto: an x-only key decodes into curves::secp256k1::xonly_public_key+` -The fix: A 32-byte x-only key decodes into `+crypto::curves::secp256k1::xonly_public_key+`: `+crypto::decode(crypto::formats::raw(crypto::formats::xonly), bytes)+`, or its member `+xonly_public_key::decode+`; `+raw(crypto::formats::xonly)+` encodes a public key's x-only key, and its 33- or 65-byte SEC 1 point decodes into a `+public_key+` with `+crypto::formats::raw+`. +The fix: A 32-byte x-only key decodes into `+crypto::curves::secp256k1::xonly_public_key+`: `+codecs::decode(crypto::formats::raw(crypto::formats::xonly), bytes)+`, or its member `+xonly_public_key::decode+`; `+raw(crypto::formats::xonly)+` encodes a public key's x-only key, and its 33- or 65-byte SEC 1 point decodes into a `+public_key+` with `+crypto::formats::raw+`. |=== At build and link time, from the fixtures of the user's Jamfiles, each built on a scratch superproject: the texts the build's output contains, per target and linker, as each fixture checks them. @@ -2062,13 +2086,17 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Call `+webcpp::secure::erase_secret+`, from `++`, the same erasure; `+crypto::erase_secret+` moved to webcpp::secure, with no alias. +|`+foreign_format_on_key+` +|the compile +|Encode or decode a key in one of the formats of its list, the `+codecs::format_list+` the assertion names; for its bytes in hexadecimal, compose a format of its list, `+codecs::over{codecs::formats::hex, crypto::formats::raw}+`. + |`+format_header_missing_toy+` |the compile |Include the formats header of the type's curve, the one the assertion names, `+/formats.hpp>+`, beside the curve's own header, which declares no format. |`+format_refused_toy+` |the compile -|Encode or decode a type in a format of its list, the `+format_list+` the assertion names: another type's format (`+der+` is an ECDSA signature's, `+pkcs8+` a key pair's) does not convert it. +|Encode or decode a type in a format of its list, the `+codecs::format_list+` the assertion names: another type's format (`+der+` is an ECDSA signature's, `+pkcs8+` a key pair's) does not convert it. |`+format_without_header+` |the compile @@ -2130,6 +2158,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Call the factory named by its input, member or free: `+from_secret+` for a key pair, `+from_bytes+` for a public key, `+from_key+` for a cipher (`+crypto::from_secret(bytes)+`, `+K::from_secret(bytes)+`); `+make+` is gone, with no alias. +|`+member_der_on_ed25519+` +|the compile +|As `+der_on_ed25519+`: encode an Ed25519 signature with `+signature.encode(crypto::formats::raw)+`, or `+codecs::encode(crypto::formats::raw, signature)+`: its 64 bytes are the signature, and it has no DER form. + |`+memory_missing_definition_from_key+` |the link |Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. @@ -2184,7 +2216,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+pem_decode_from_bytes+` |the compile -|Give a PEM to `+crypto::decode+` or `+codecs::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. +|Give a PEM to `+codecs::decode+`, or a type's member `+decode+`, as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. |`+pem_header_removed+` |the compile @@ -2202,6 +2234,14 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |As `+pem_of_der+`: armor the DER of a key, `+crypto::formats::pem(crypto::formats::spki)+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`; a key's raw bytes have no PEM. +|`+pem_other_armor+` +|the compile +|Encode or decode a key's PEM with `+crypto::formats::pem(crypto::formats::spki)+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`, whose label, `+PUBLIC KEY+` or `+PRIVATE KEY+`, is in its type; a text under another label, a certificate's among them, is no key, and decoding it gives `+codecs::error::invalid_prefix+`. + +|`+pem_other_basic_armor+` +|the compile +|As `+pem_other_armor+`: name a key's PEM by `+crypto::formats::pem(F)+`, never by `+codecs::formats::basic_armor+` of a label, so that the label is always the inner format's. + |`+ph_removed+` |the compile |Name Ed25519ph's streaming signer `+curves::ed25519::prehashed_signer+`, the same `+begin+`, `+update+`, `+sign+` and `+verify+`; `+curves::ed25519::ph+` is gone, with no alias. @@ -2520,7 +2560,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+xonly_into_public_key+` |the compile -|A 32-byte x-only key decodes into `+crypto::curves::secp256k1::xonly_public_key+`: `+crypto::decode(crypto::formats::raw(crypto::formats::xonly), bytes)+`, or its member `+xonly_public_key::decode+`; `+raw(crypto::formats::xonly)+` encodes a public key's x-only key, and its 33- or 65-byte SEC 1 point decodes into a `+public_key+` with `+crypto::formats::raw+`. +|A 32-byte x-only key decodes into `+crypto::curves::secp256k1::xonly_public_key+`: `+codecs::decode(crypto::formats::raw(crypto::formats::xonly), bytes)+`, or its member `+xonly_public_key::decode+`; `+raw(crypto::formats::xonly)+` encodes a public key's x-only key, and its 33- or 65-byte SEC 1 point decodes into a `+public_key+` with `+crypto::formats::raw+`. |=== Elsewhere than MSVC these mistakes build, and nothing stops them; the fixtures record it: diff --git a/doc/llms.txt b/doc/llms.txt index b413455b..9e6c4f77 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -167,8 +167,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - public_key::decode: Decodes a public key from `input` in `format`, as `crypto::decode` does. - basic_keypair::encode: Encodes the key pair in `format`, as `crypto::encode(format, key_pair)` does. - basic_keypair::decode: Decodes a key pair from `input` in `format`, as `crypto::decode` does. - - basic_signature::encode: Encodes the signature in `format`, as `crypto::encode(format, signature)` does. - - basic_signature::decode: Decodes a signature from `input` in `format`, as `crypto::decode` does. + - basic_signature::encode: Encodes the signature in `format`, as `codecs::encode(format, signature)` does. + - basic_signature::decode: Decodes a signature from `input` in `format`, as `codecs::decode` does. - [crypto::encode, crypto::decode, curves::x25519::public_key::encode, curves::x25519::public_key::decode, curves::x25519::keypair::encode, curves::x25519::keypair::decode](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): X25519's formats as codecs value codecs: a public key's `formats::raw` (32 bytes), `formats::spki` (RFC 8410, 44 bytes) and `formats::pem(formats::spki)`; a key pair's `formats::raw` (its secret key), `formats::pkcs8` (RFC 8410's version 1, 48 bytes) and `formats::pem(formats::pkcs8)`, secret; the forms OpenSSL and WebCrypto write, an SPKI decoded into the typed key, the DER decoded strictly: any other bytes are `invalid_encoding`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text. - public_key::encode: Encodes the key in `format`, as `crypto::encode(format, key)` does. - public_key::decode: Decodes a public key from `input` in `format`, as `crypto::decode` does. @@ -198,8 +198,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - basic_keypair::encode: Encodes the key pair in `format`, as `crypto::encode(format, key_pair)` does. - basic_keypair::decode: Decodes a key pair from `input` in `format`, as `crypto::decode` does. - basic_keypair::decode(std::pmr::memory_resource): Decodes a key pair from `input` in `format`, its signing context from `memory_resource`, as `from_secret` with a resource takes it: the decode without a resource, which takes the context from `std::pmr::get_default_resource()`, into the program's own arena. - - basic_signature::encode: Encodes the signature in `format`, as `crypto::encode(format, signature)` does. - - basic_signature::decode: Decodes a signature from `input` in `format`, as `crypto::decode` does. + - basic_signature::encode: Encodes the signature in `format`, as `codecs::encode(format, signature)` does. + - basic_signature::decode: Decodes a signature from `input` in `format`, as `codecs::decode` does. - [curves::secp256k1::ellswift_encode, ellswift_decode, ellswift_create, ellswift_xdh](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ellswift): A public key written as 64 bytes that look random, and BIP 324's key exchange of two such encodings. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's). - ellswift_encode: A public key's ElligatorSwift encoding (`secp256k1_ellswift_encode`): one of many, chosen by the randomness, each of which decodes to the key. - ellswift_decode: The public key of any 64 bytes (`secp256k1_ellswift_decode`): every input decodes. @@ -261,8 +261,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - basic_public_key::decode: Decodes a public key from `input` in `format`, as `crypto::decode` does. - basic_keypair::encode: Encodes the key pair in `format`, as `crypto::encode(format, key_pair)` does. - basic_keypair::decode: Decodes a key pair from `input` in `format`, as `crypto::decode` does. - - basic_signature::encode: Encodes the signature in `format`, as `crypto::encode(format, signature)` does. - - basic_signature::decode: Decodes a signature from `input` in `format`, as `crypto::decode` does. + - basic_signature::encode: Encodes the signature in `format`, as `codecs::encode(format, signature)` does. + - basic_signature::decode: Decodes a signature from `input` in `format`, as `codecs::decode` does. ## webcpp::crypto::public_key_encryption diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 50d5230d..c7bd125b 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1446,7 +1446,7 @@ "verify_schnorr_as_ecdsa": "Verify a BIP340 signature with `crypto::signing_schemes::schnorr`, its scheme; `crypto::signing_schemes::ecdsa_sha256` takes a `curves::secp256k1::ecdsa_signature`, which `sign(crypto::signing_schemes::ecdsa_sha256, input)` gives.", "verify_ed25519_bytes_signature": "Make the 64 bytes received into a `curves::ed25519::signature` with `curves::ed25519::signature::from_bytes`, which checks their size, and verify that.", "low_s_on_ed25519": "Only an ECDSA signature has low S: Ed25519 and Schnorr signatures have no `is_low_s()` or `low_s()`, and need none, for no other S verifies as theirs.", - "format_refused_toy": "Encode or decode a type in a format of its list, the `format_list` the assertion names: another type's format (`der` is an ECDSA signature's, `pkcs8` a key pair's) does not convert it.", + "format_refused_toy": "Encode or decode a type in a format of its list, the `codecs::format_list` the assertion names: another type's format (`der` is an ECDSA signature's, `pkcs8` a key pair's) does not convert it.", "pem_of_der": "Armor the DER of a key: `crypto::formats::pem(crypto::formats::spki)` for a public key, `crypto::formats::pem(crypto::formats::pkcs8)` for a key pair; a signature's DER has no PEM.", "pem_of_raw": "As `pem_of_der`: armor the DER of a key, `crypto::formats::pem(crypto::formats::spki)` or `crypto::formats::pem(crypto::formats::pkcs8)`; a key's raw bytes have no PEM.", "format_header_missing_toy": "Include the formats header of the type's curve, the one the assertion names, `/formats.hpp>`, beside the curve's own header, which declares no format.", @@ -1455,7 +1455,7 @@ "format_without_header": "Include ``, or the curve's `/formats.hpp>`, which includes it: `crypto::formats` is declared by `config.hpp` and filled by the formats headers alone.", "decode_refusal_reason_toy": "Decode the x-only form into the type that holds it, as secp256k1's `curves::secp256k1::xonly_public_key`; the type this refuses has the form to encode only.", "refusal_reason_toy": "Encode the signature with `crypto::formats::raw`: an Ed25519 or BIP340 signature has no DER form, its 64 bytes are the signature.", - "pem_decode_from_bytes": "Give a PEM to `crypto::decode` or `codecs::decode` as a text: a `std::string_view`, a `std::string`, or a contiguous sized range of `char` such as `std::span`; DER bytes decode with `crypto::formats::spki` or `crypto::formats::pkcs8` themselves.", + "pem_decode_from_bytes": "Give a PEM to `codecs::decode`, or a type's member `decode`, as a text: a `std::string_view`, a `std::string`, or a contiguous sized range of `char` such as `std::span`; DER bytes decode with `crypto::formats::spki` or `crypto::formats::pkcs8` themselves.", "forms_without_default": "List `crypto::formats::default_form_t` in each `detail::forms_of` specialization, with the other point forms the type accepts.", "der_on_ed25519": "Encode an Ed25519 signature with `crypto::formats::raw`, or its member `signature.encode(crypto::formats::raw)`: its 64 bytes are the signature, and it has no DER form.", "ed25519_formats_header_missing": "Include ``, which registers Ed25519's formats, beside ``.", @@ -1465,11 +1465,15 @@ "raw_on_asynchronous_x25519": "Export the key pair with WebCrypto's `exportKey`, on the backend that keeps it, or make the key pair on a backend whose secret is in the program, libsodium, to read its secret with `crypto::formats::raw`, `crypto::formats::pkcs8` or `crypto::formats::pem(crypto::formats::pkcs8)`; its public key's formats are available on every backend.", "pem_header_removed": "Write and read PEM with `crypto::encode` and `crypto::decode` and `crypto::formats::pem(crypto::formats::spki)` or `crypto::formats::pem(crypto::formats::pkcs8)`, in ``, codecs' armor over the key's DER; `pem.hpp` is gone, with no header left at its path.", "pem_namespace_removed": "Write and read PEM with `crypto::encode` and `crypto::decode` and `crypto::formats::pem(crypto::formats::spki)` or `crypto::formats::pem(crypto::formats::pkcs8)`, which take the label from the inner format; `crypto::pem`, its `armour`, `unarmour`, labels and `armoured_size`, is gone, with no alias.", - "xonly_into_public_key": "A 32-byte x-only key decodes into `crypto::curves::secp256k1::xonly_public_key`: `crypto::decode(crypto::formats::raw(crypto::formats::xonly), bytes)`, or its member `xonly_public_key::decode`; `raw(crypto::formats::xonly)` encodes a public key's x-only key, and its 33- or 65-byte SEC 1 point decodes into a `public_key` with `crypto::formats::raw`.", + "xonly_into_public_key": "A 32-byte x-only key decodes into `crypto::curves::secp256k1::xonly_public_key`: `codecs::decode(crypto::formats::raw(crypto::formats::xonly), bytes)`, or its member `xonly_public_key::decode`; `raw(crypto::formats::xonly)` encodes a public key's x-only key, and its 33- or 65-byte SEC 1 point decodes into a `public_key` with `crypto::formats::raw`.", "der_on_recoverable": "Encode a recoverable signature with `crypto::formats::raw`, its 65 bytes, r, s and the recovery id, or its member `signature.encode(crypto::formats::raw)`; it has no DER form. A Bitcoin script's DER is that of an `ecdsa_signature`: sign with `crypto::signing_schemes::ecdsa_sha256` and encode it in `crypto::formats::der`.", "der_on_schnorr": "Encode a BIP340 signature with `crypto::formats::raw`, or its member `signature.encode(crypto::formats::raw)`: its 64 bytes are the signature, and it has no DER form.", "keypair_decode_resource_spki": "Decode a secp256k1 key pair, with or without a memory resource, from one of its formats: `crypto::formats::raw`, its secret key, `crypto::formats::pkcs8` or `crypto::formats::pem(crypto::formats::pkcs8)`; an SPKI holds a public key, which `crypto::curves::secp256k1::public_key::decode(crypto::formats::spki, bytes)` gives.", "keypair_decode_resource_from_text": "Give the key pair's decode with a memory resource bytes for `crypto::formats::raw` and `crypto::formats::pkcs8`, a `std::span` or what converts to one (`std::array`, `std::vector`, a result's `view()`); a PEM text decodes with `crypto::formats::pem(crypto::formats::pkcs8)`.", + "pem_other_armor": "Encode or decode a key's PEM with `crypto::formats::pem(crypto::formats::spki)` or `crypto::formats::pem(crypto::formats::pkcs8)`, whose label, `PUBLIC KEY` or `PRIVATE KEY`, is in its type; a text under another label, a certificate's among them, is no key, and decoding it gives `codecs::error::invalid_prefix`.", + "pem_other_basic_armor": "As `pem_other_armor`: name a key's PEM by `crypto::formats::pem(F)`, never by `codecs::formats::basic_armor` of a label, so that the label is always the inner format's.", + "member_der_on_ed25519": "As `der_on_ed25519`: encode an Ed25519 signature with `signature.encode(crypto::formats::raw)`, or `codecs::encode(crypto::formats::raw, signature)`: its 64 bytes are the signature, and it has no DER form.", + "foreign_format_on_key": "Encode or decode a key in one of the formats of its list, the `codecs::format_list` the assertion names; for its bytes in hexadecimal, compose a format of its list, `codecs::over{codecs::formats::hex, crypto::formats::raw}`.", "x25519_formats_header_missing": "Include ``, which registers X25519's formats, beside ``.", "recover_ecdsa_signature": "Give `recover` a `curves::secp256k1::recoverable_signature`, which `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, input)` gives, or made from 65 bytes with `from_bytes`; an ECDSA signature without its recovery id verifies with `crypto::verify` and the signer's public key.", "async_verify_p256_bytes_signature": "As `verify_p256_secp256k1_signature`: make the 64 bytes received into a `curves::p256::ecdsa_signature` with `from_bytes`, then give it to `async_verify`.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 6b58e7e5..ecc45760 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1749,7 +1749,7 @@ def ed25519_cases_page(data: Data, cases: Data) -> str: # The library's one list of formats, detail::all_formats, as formats.hpp declares it: the formats # table's columns are its formats, which crypto.json's `formats` list must name in its order. FORMATS_HEADER = Path('include/webcpp/crypto/formats.hpp') -ALL_FORMATS = re.compile(r'using all_formats\s*=\s*format_list<(.*?)>;', re.S) +ALL_FORMATS = re.compile(r'using all_formats\s*=\s*codecs::format_list<(.*?)>;', re.S) # A format of the list as formats.hpp writes it: `formats::raw_t<>`, `formats::pkcs8_t`, # `formats::pem_t>`. FORMAT_TYPE = re.compile(r'formats::([a-z0-9]+)_t(?:<>)?') @@ -1769,7 +1769,7 @@ def compiled_formats(header: Path) -> List[str]: or a format the reader cannot name, is a fault.""" found = ALL_FORMATS.search(header.read_text(encoding='utf-8')) if found is None: - raise Fault(f'{header.name} declares no `using all_formats = format_list<...>;`') + raise Fault(f'{header.name} declares no `using all_formats = codecs::format_list<...>;`') entries: List[str] = [] depth, start = 0, 0 text = found.group(1) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index acb91677..7d232520 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -1233,10 +1233,10 @@ def test_an_example_s_description_holding_a_tag_directive_is_a_fault(scratch: Pa # The library's list as formats.hpp declares it, the shape the reader takes. ALL_FORMATS_TEXT = ( - 'template \nstruct format_list {};\n\n' '/** The library\'s one list of formats. */\nusing all_formats =\n' - ' format_list, formats::spki_t<>, formats::pkcs8_t, formats::der_t,\n' - ' formats::pem_t>, formats::pem_t>;\n') + ' codecs::format_list, formats::spki_t<>, formats::pkcs8_t,\n' + ' formats::der_t, formats::pem_t>,\n' + ' formats::pem_t>;\n') COMPILED = ['raw', 'spki', 'pkcs8', 'der', 'pem(spki)', 'pem(pkcs8)'] @@ -1271,7 +1271,7 @@ def test_the_compiled_list_is_read_from_formats_hpp(scratch: Path) -> None: assert 'formats::jwk' in str(fault), fault else: raise AssertionError('a format the reader cannot name was read') - none = written(scratch, 'none.hpp', 'struct format_list {};\n') + none = written(scratch, 'none.hpp', 'using all_formats = format_list>;\n') try: generate.compiled_formats(none) except generate.Fault as fault: diff --git a/include/webcpp/crypto/curves/ed25519/formats.hpp b/include/webcpp/crypto/curves/ed25519/formats.hpp index 2961a2c6..e8ded952 100644 --- a/include/webcpp/crypto/curves/ed25519/formats.hpp +++ b/include/webcpp/crypto/curves/ed25519/formats.hpp @@ -10,14 +10,14 @@ WebCrypto's `exportKey("spki")` write; a key pair's `formats::raw`, its seed, and `formats::pkcs8`, RFC 8410's version 1, the 48 bytes of the seed alone that OpenSSL's `i2d_PrivateKey` and WebCrypto's `exportKey("pkcs8")` write, both secret; `formats::pem` of - either DER, through codecs' armor; and a signature's `formats::raw`, its 64 bytes. Each is a - `codecs::value_codec`, which `crypto::encode`, `crypto::decode`, codecs' verbs and the types' - members `encode` and `decode`, defined here, call. The DER formats decode strictly, the one - encoding that encoding the key again gives (design D30): any other bytes, a version 2 PKCS#8 - among them, are `invalid_encoding`. + either DER, through codecs' `basic_armor`, its label in its type; and a signature's `formats::raw`, + its 64 bytes. Each is a `codecs::value_codec`, which codecs' verbs, `codecs::encode` and + `codecs::decode`, and the types' members `encode` and `decode`, defined here, call. The DER formats + decode strictly, the one encoding that encoding the key again gives (design D30): any other bytes, + a version 2 PKCS#8 among them, are `invalid_encoding`. The key pair's private formats exist on a backend whose secret is in the program; on a backend - whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), `crypto::encode` refuses + whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), codecs' verbs refuse them, naming WebCrypto's `exportKey` (design D7). A public key, which names no backend, is encoded and decoded on the family's default, libsodium on every target. @@ -133,7 +133,7 @@ template <> struct formats_of { /** Its formats. */ using type = - format_list, formats::spki_t<>, formats::pem_t>>; + codecs::format_list, formats::spki_t<>, formats::pem_t>>; }; /** @@ -144,14 +144,15 @@ struct formats_of { template struct formats_of> { /** Its formats. */ - using type = format_list, formats::pkcs8_t, formats::pem_t>; + using type = + codecs::format_list, formats::pkcs8_t, formats::pem_t>; }; /** An Ed25519 signature has `raw`, its 64 bytes. */ template <> struct formats_of { /** Its formats. */ - using type = format_list>; + using type = codecs::format_list>; }; /** An Ed25519 signature has no DER form: its 64 bytes are the signature (design D3). */ @@ -557,61 +558,61 @@ static_assert(::webcpp::crypto::detail::check_bounds< namespace webcpp::crypto::curves::ed25519 { /** - * Encodes the key in `format`: the member form of `crypto::encode`. + * Encodes the key in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template auto public_key::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a public key from `input` in `format`: the member form of `crypto::decode`. + * Decodes a public key from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template auto public_key::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } /** - * Encodes the key pair in `format`: the member form of `crypto::encode`. + * Encodes the key pair in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template template auto basic_keypair::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a key pair from `input` in `format`: the member form of `crypto::decode`. + * Decodes a key pair from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template template auto basic_keypair::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } } // namespace webcpp::crypto::curves::ed25519 diff --git a/include/webcpp/crypto/curves/p256/formats.hpp b/include/webcpp/crypto/curves/p256/formats.hpp index 9194f7b3..fae47d84 100644 --- a/include/webcpp/crypto/curves/p256/formats.hpp +++ b/include/webcpp/crypto/curves/p256/formats.hpp @@ -11,10 +11,10 @@ 91 bytes, which OpenSSL's `i2d_PUBKEY` and WebCrypto's `exportKey("spki")` write, or 59 around the compressed point; a key pair's `formats::raw`, its secret scalar, and `formats::pkcs8`, RFC 5208 around RFC 5915's ECPrivateKey with its public key and no parameters, 138 bytes, both secret; - `formats::pem` of either DER, through codecs' armor; and a signature's `formats::raw`, r then s, - 64 bytes, and `formats::der`, strict DER, 8 to 72 bytes. Each is a `codecs::value_codec`, which - `crypto::encode`, `crypto::decode`, codecs' verbs and the types' members `encode` and `decode`, - defined here, call. + `formats::pem` of either DER, through codecs' `basic_armor`, its label in its type; and a + signature's `formats::raw`, r then s, 64 bytes, and `formats::der`, strict DER, 8 to 72 bytes. Each + is a `codecs::value_codec`, which codecs' verbs, `codecs::encode` and `codecs::decode`, and the + types' members `encode` and `decode`, defined here, call. Each decoder accepts exactly what its encoder writes (design D30); a format named without a point form decodes both forms, the uncompressed and the compressed. A compressed point is decoded @@ -23,7 +23,7 @@ checked as every point is (design R16, as the owner amended it on 2026-12-01). The key pair's private formats exist on a backend whose secret is in the program; on a backend - whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), `crypto::encode` refuses + whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), codecs' verbs refuse them, naming WebCrypto's `exportKey` (design D7). A signature, which names no backend, is converted to and from DER on the family's default, BearSSL on every target. @@ -176,7 +176,7 @@ template struct formats_of> { /** Its formats. */ using type = - format_list, formats::spki_t<>, formats::pem_t>>; + codecs::format_list, formats::spki_t<>, formats::pem_t>>; }; /** @@ -210,14 +210,15 @@ struct forms_of, curves::p256::basic_public_key> { template struct formats_of> { /** Its formats. */ - using type = format_list, formats::pkcs8_t, formats::pem_t>; + using type = + codecs::format_list, formats::pkcs8_t, formats::pem_t>; }; /** A P-256 ECDSA signature has `raw`, r then s, and `der` (design D6). */ template <> struct formats_of { /** Its formats. */ - using type = format_list, formats::der_t>; + using type = codecs::format_list, formats::der_t>; }; /** @@ -824,63 +825,63 @@ static_assert(::webcpp::crypto::detail::check_bounds< namespace webcpp::crypto::curves::p256 { /** - * Encodes the key in `format`: the member form of `crypto::encode`. + * Encodes the key in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template template auto basic_public_key::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a public key from `input` in `format`: the member form of `crypto::decode`. + * Decodes a public key from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template template auto basic_public_key::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } /** - * Encodes the key pair in `format`: the member form of `crypto::encode`. + * Encodes the key pair in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template template auto basic_keypair::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a key pair from `input` in `format`: the member form of `crypto::decode`. + * Decodes a key pair from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template template auto basic_keypair::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } } // namespace webcpp::crypto::curves::p256 diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp index c7e47f7e..e8532555 100644 --- a/include/webcpp/crypto/curves/secp256k1/formats.hpp +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -14,11 +14,11 @@ `formats::raw`, its 32 bytes, BIP340's lift of x; a key pair's `formats::raw`, its secret key, and `formats::pkcs8`, RFC 5208 around RFC 5915's ECPrivateKey with its uncompressed public key and no parameters, 135 bytes, as OpenSSL writes it, both secret; `formats::pem` of either DER, - through codecs' armor; an ECDSA signature's `formats::raw`, r then s, 64 bytes, and `formats::der`, - strict DER (BIP66), 8 to 72 bytes, through libsecp256k1's own encoder and parser; and the - recoverable signature's and the BIP340 signature's `formats::raw`, 65 and 64 bytes. Each is a - `codecs::value_codec`, which `crypto::encode`, `crypto::decode`, codecs' verbs and the types' - members `encode` and `decode`, defined here, call. + through codecs' `basic_armor`, its label in its type; an ECDSA signature's `formats::raw`, r then + s, 64 bytes, and `formats::der`, strict DER (BIP66), 8 to 72 bytes, through libsecp256k1's own + encoder and parser; and the recoverable signature's and the BIP340 signature's `formats::raw`, 65 + and 64 bytes. Each is a `codecs::value_codec`, which codecs' verbs, `codecs::encode` and + `codecs::decode`, and the types' members `encode` and `decode`, defined here, call. Each decoder accepts exactly what its encoder writes (design D30); a format named without a point form decodes both forms, so that an SPKI stored compressed, the former default, still decodes @@ -279,7 +279,7 @@ template <> struct formats_of { /** Its formats. */ using type = - format_list, formats::spki_t<>, formats::pem_t>>; + codecs::format_list, formats::spki_t<>, formats::pem_t>>; }; /** @@ -316,7 +316,7 @@ inline constexpr refusal_reason template <> struct formats_of { /** Its formats. */ - using type = format_list>; + using type = codecs::format_list>; }; /** An x-only key's `raw` is its 32 bytes, by default and as `raw(xonly)`. */ @@ -334,28 +334,29 @@ struct forms_of, curves::secp256k1::xonly_public_key> { template struct formats_of> { /** Its formats. */ - using type = format_list, formats::pkcs8_t, formats::pem_t>; + using type = + codecs::format_list, formats::pkcs8_t, formats::pem_t>; }; /** A secp256k1 ECDSA signature has `raw`, r then s, and `der` (design D6). */ template <> struct formats_of { /** Its formats. */ - using type = format_list, formats::der_t>; + using type = codecs::format_list, formats::der_t>; }; /** A recoverable signature has `raw`, r, s and the recovery id. */ template <> struct formats_of { /** Its formats. */ - using type = format_list>; + using type = codecs::format_list>; }; /** A BIP340 signature has `raw`, its 64 bytes. */ template <> struct formats_of { /** Its formats. */ - using type = format_list>; + using type = codecs::format_list>; }; /** A BIP340 signature has no DER form: its 64 bytes are the signature (design D3). */ @@ -453,7 +454,7 @@ struct value_codec, crypto::curves::secp256k1::publ /** * A secp256k1 public key's `formats::raw(formats::xonly)`: its BIP340 x-only key's 32 bytes, * `xonly().bytes()` under the format's name, to encode only: 32 bytes decode into a - * `curves::secp256k1::xonly_public_key`, and `crypto::decode` of this pair stops the build saying + * `curves::secp256k1::xonly_public_key`, and `codecs::decode` of this pair stops the build saying * so (design D3, D4). It holds `secure::timing_guard`: libsecp256k1 drops the parity of y. */ template <> @@ -1153,101 +1154,103 @@ static_assert(::webcpp::crypto::detail::check_bounds< namespace webcpp::crypto::curves::secp256k1 { /** - * Encodes the key in `format`: the member form of `crypto::encode`. + * Encodes the key in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template auto public_key::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a public key from `input` in `format`: the member form of `crypto::decode`. + * Decodes a public key from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template auto public_key::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } /** - * Encodes the x-only key in `format`: the member form of `crypto::encode`. + * Encodes the x-only key in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template auto xonly_public_key::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes an x-only key from `input` in `format`: the member form of `crypto::decode`. + * Decodes an x-only key from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template auto xonly_public_key::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } /** - * Encodes the key pair in `format`: the member form of `crypto::encode`. + * Encodes the key pair in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template template auto basic_keypair::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a key pair from `input` in `format`: the member form of `crypto::decode`. + * Decodes a key pair from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template template auto basic_keypair::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } /** * Decodes a key pair from `input` in `format`, its signing context from `memory_resource`: the - * pair checked as `crypto::decode` checks it, then the detail decode the value codec runs with the - * default resource (design R2), run with the caller's. + * pair checked by `codecs::check_conversion`, with the diagnostics of codecs' verbs (crypto's + * sentence, or codecs' message with the type's list), then the detail decode the value codec runs + * with the default resource (design R2, R13), run with the caller's. * * An input longer than the pair's decode bound, `formats::max_decode_input_size`, is * `codecs::error::input_too_long`, as `codecs::decode` gives it, before the detail decode reads a - * byte. A PEM is decoded by codecs' typed decode of its armor, with the inner format's label, into - * a `codecs::secret_bytes` of the PKCS#8's decode bound (no heap, wiped when it goes, the armor's - * errors first, a payload past the bound `input_too_long`), then the detail decode of its DER. + * byte. A PEM is decoded by codecs' typed decode of its armor, `format.outer`, whose label is the + * inner format's, into a `codecs::secret_bytes` of the PKCS#8's decode bound (no heap, wiped when + * it goes, the armor's errors first, a payload past the bound `input_too_long`), then the detail + * decode of its DER. * * @tparam Format The format's type. * @tparam Input The input's type. @@ -1262,14 +1265,14 @@ auto basic_keypair::decode(Format const& format, Input const& input, std::pmr::memory_resource* memory_resource) { using result_type = boost::system::result; secure::timing_guard const timing_scope; - if constexpr (!detail::pair_accepted()) { - detail::refuse_pair(); + codecs::check_conversion(); + if constexpr (!codecs::decodable) { + // Unreachable once the check stops the build: an error, never a value. return result_type{error::invalid_encoding}; } else if constexpr (std::is_same_v>) { constexpr std::size_t bound = formats::max_decode_input_size; - auto const der_bytes = codecs::decode>( - detail::pem_armor_of(format), input); + auto const der_bytes = codecs::decode>(format.outer, input); if (!der_bytes) { // A payload past the bound does not fit: the error over gives past the same bound. if (der_bytes.error() == codecs::error::output_too_small) { diff --git a/include/webcpp/crypto/curves/x25519/formats.hpp b/include/webcpp/crypto/curves/x25519/formats.hpp index 23b8858c..42e9d5de 100644 --- a/include/webcpp/crypto/curves/x25519/formats.hpp +++ b/include/webcpp/crypto/curves/x25519/formats.hpp @@ -10,14 +10,14 @@ `i2d_PUBKEY` and WebCrypto's `exportKey("spki")` write; a key pair's `formats::raw`, its secret key, and `formats::pkcs8`, RFC 8410's version 1, the 48 bytes of the secret key alone that OpenSSL's `i2d_PrivateKey` and WebCrypto's `exportKey("pkcs8")` write, both secret; and - `formats::pem` of either DER, through codecs' armor. Each is a `codecs::value_codec`, which - `crypto::encode`, `crypto::decode`, codecs' verbs and the types' members `encode` and `decode`, - defined here, call. The DER formats decode strictly, the one encoding that encoding the key - again gives (design D30): any other bytes, a version 2 PKCS#8 among them, are - `invalid_encoding`. + `formats::pem` of either DER, through codecs' `basic_armor`, its label in its type. Each is a + `codecs::value_codec`, which codecs' verbs, `codecs::encode` and `codecs::decode`, and the types' + members `encode` and `decode`, defined here, call. The DER formats decode strictly, the one + encoding that encoding the key again gives (design D30): any other bytes, a version 2 PKCS#8 among + them, are `invalid_encoding`. The key pair's private formats exist on a backend whose secret is in the program; on a backend - whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), `crypto::encode` refuses + whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), codecs' verbs refuse them, naming WebCrypto's `exportKey` (design D7). A public key, which names no backend, is encoded and decoded on the family's default, libsodium on every target. @@ -97,7 +97,7 @@ template <> struct formats_of { /** Its formats. */ using type = - format_list, formats::spki_t<>, formats::pem_t>>; + codecs::format_list, formats::spki_t<>, formats::pem_t>>; }; /** @@ -108,7 +108,8 @@ struct formats_of { template struct formats_of> { /** Its formats. */ - using type = format_list, formats::pkcs8_t, formats::pem_t>; + using type = + codecs::format_list, formats::pkcs8_t, formats::pem_t>; }; /** @@ -449,61 +450,61 @@ static_assert(::webcpp::crypto::detail::check_bounds<::webcpp::crypto::formats:: namespace webcpp::crypto::curves::x25519 { /** - * Encodes the key in `format`: the member form of `crypto::encode`. + * Encodes the key in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template auto public_key::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a public key from `input` in `format`: the member form of `crypto::decode`. + * Decodes a public key from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template auto public_key::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } /** - * Encodes the key pair in `format`: the member form of `crypto::encode`. + * Encodes the key pair in `format`: the member form of `codecs::encode`. * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template template auto basic_keypair::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a key pair from `input` in `format`: the member form of `crypto::decode`. + * Decodes a key pair from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template template auto basic_keypair::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } } // namespace webcpp::crypto::curves::x25519 diff --git a/include/webcpp/crypto/detail/format_members.hpp b/include/webcpp/crypto/detail/format_members.hpp index 380fe021..b92f0fd5 100644 --- a/include/webcpp/crypto/detail/format_members.hpp +++ b/include/webcpp/crypto/detail/format_members.hpp @@ -5,11 +5,11 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - What the members `encode` and `decode` of crypto's value types declare (design D2): the traits + What the members `encode` and `decode` of crypto's value types declare (design D1): the traits `detail::encode_is_noexcept` and `detail::decode_is_noexcept`, whose answer each member's - exception specification is, as the verbs `crypto::encode` and `crypto::decode` it calls give - theirs. Declared here, with no codecs header, so that a curve's own header and the signature - template declare their members; `` defines them. + exception specification is, the one codecs' verbs `codecs::encode` and `codecs::decode` it calls + give for the same arguments. Declared here, with no codecs header, so that a curve's own header + and the signature template declare their members; `` defines them. */ #ifndef WEBCPP_CRYPTO_DETAIL_FORMAT_MEMBERS_HPP #define WEBCPP_CRYPTO_DETAIL_FORMAT_MEMBERS_HPP @@ -19,7 +19,7 @@ namespace webcpp::crypto::detail { /** - * Whether `crypto::encode` of `Value` in `Format`, with `Rest`, cannot throw: codecs' verb's own + * Whether `codecs::encode` of `Value` in `Format`, with `Rest`, cannot throw: codecs' verb's own * answer, true for every pair of crypto's into its default result or a span (`formats.hpp` * defines it). * @@ -32,9 +32,9 @@ template consteval bool encode_is_noexcept(); /** - * Whether `crypto::decode` of `Input` in `Format` cannot throw: true for every pair of - * crypto's but a key pair whose decode allocates from a memory resource (secp256k1's signing - * context) (`formats.hpp` defines it). + * Whether `codecs::decode` of `Input` in `Format` cannot throw: codecs' verb's own answer, + * true for every pair of crypto's but a key pair whose decode allocates from a memory resource + * (secp256k1's signing context) (`formats.hpp` defines it). * * @tparam Value The value's type. * @tparam Format The format's type. diff --git a/include/webcpp/crypto/detail/signature.hpp b/include/webcpp/crypto/detail/signature.hpp index 668968b3..19145742 100644 --- a/include/webcpp/crypto/detail/signature.hpp +++ b/include/webcpp/crypto/detail/signature.hpp @@ -132,7 +132,7 @@ class basic_signature { } /** - * Encodes the signature in `format`, as `crypto::encode(format, signature)` does. + * Encodes the signature in `format`, as `codecs::encode(format, signature)` does. * * The formats are `formats::raw`, its bytes, and, for an ECDSA signature, `formats::der`. * Defined by ``, which the curve's formats header includes: @@ -140,14 +140,14 @@ class basic_signature { * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, signature)` returns. + * @return What `codecs::encode(format, signature)` returns. */ template [[nodiscard]] auto encode(Format const& format) const noexcept(detail::encode_is_noexcept()); /** - * Decodes a signature from `input` in `format`, as `crypto::decode` does. + * Decodes a signature from `input` in `format`, as `codecs::decode` does. * * Defined by ``, as `encode` is. * @@ -155,7 +155,7 @@ class basic_signature { * @tparam Input The input's type: bytes. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template [[nodiscard]] static auto decode(Format const& format, Input const& input) noexcept( diff --git a/include/webcpp/crypto/formats.hpp b/include/webcpp/crypto/formats.hpp index 3da8fc47..dc06b829 100644 --- a/include/webcpp/crypto/formats.hpp +++ b/include/webcpp/crypto/formats.hpp @@ -8,20 +8,23 @@ The formats of keys and signatures, registered into webcpp::codecs (design D1, D2, D3 and D11): the format tags `formats::raw`, `formats::spki`, `formats::pkcs8` and `formats::der`, each a `codecs::format`; the point forms `formats::compressed`, `formats::uncompressed` and - `formats::xonly`, which `raw(form)` and `spki(form)` take; `formats::pem(inner)`, codecs' armor - over `spki` or `pkcs8` with the label of the inner format; the library's one list of formats, - `detail::all_formats`, and the traits each value type declares its own with - (`detail::formats_of`, `detail::forms_of`, `detail::curve_of_v`, the refusal reasons); the two - bounds of a value codec, `formats::max_encoded_size` and `formats::max_decode_input_size`; and the - verbs `crypto::encode` and `crypto::decode`, which check a pair of crypto's against the type's - list and then call codecs' verbs, which decode a PEM in place; and the members `encode` and - `decode` of every signature type (`detail::basic_signature`), which call the verbs. + `formats::xonly`, which `raw(form)` and `spki(form)` take; `formats::pem(inner)`, codecs' + `basic_armor` over `spki` or `pkcs8` with the inner format's label in its type + (`detail::pem_label`); the library's one list of formats, `detail::all_formats`, and the traits + each value type declares its own with (`detail::formats_of`, `detail::forms_of`, + `detail::curve_of_v`, the refusal reasons); the two bounds of a value codec, + `formats::max_encoded_size` and `formats::max_decode_input_size`; crypto's declaration of every + one of its value types to codecs, `codecs::value_formats` (the type's list and the reasons of + crypto's sentences), through which `codecs::encode` and `codecs::decode` check every pair; the + members `encode` and `decode` of every signature type (`detail::basic_signature`), which call + codecs' verbs; and `crypto::encode` and `crypto::decode`, forwards to codecs' verbs that are + removed in a later step of this change. Each pair of a format and a type is a `codecs::value_codec` specialization in the type's curve's `curves//formats.hpp`; this header includes no curve and no backend, and is the only one, - with those, that includes a codecs header. A program may call `codecs::encode` and - `codecs::decode` with the same formats: it gets the same bytes and the same values, and - codecs' generic diagnostic for a pair that does not exist. + with those, that includes a codecs header. codecs' verbs are crypto's: a pair a type does not + have stops the build with one error, crypto's sentence (reported in this header) for a reason of + crypto's, or codecs' message with the type's list (reported in codecs' header). @see "Key formats: raw, SPKI, PKCS#8, DER and PEM", in the guide. */ @@ -238,21 +241,28 @@ inline constexpr der_t der{}; namespace detail { /** - * The label of the PEM of `Inner`: `"PUBLIC KEY"` for every `formats::spki_t
` and - * `"PRIVATE KEY"` for `formats::pkcs8_t` (RFC 7468); empty for any other, which `pem` refuses. + * The label of the PEM of `Inner`, the `Label` of codecs' `basic_armor` in `formats::pem_t` + * (RFC 7468): its `value` is `"PUBLIC KEY"` for every `formats::spki_t` and `"PRIVATE KEY"` + * for `formats::pkcs8_t`. Undefined for any other format, which `pem` refuses. * * @tparam Inner The format inside the armor. */ template -inline constexpr std::string_view pem_label_v{}; +struct pem_label; /** An SPKI's armor is labelled `PUBLIC KEY`, whatever its point form. */ template -inline constexpr std::string_view pem_label_v> = "PUBLIC KEY"; +struct pem_label> { + /** The label. */ + static constexpr std::string_view value = "PUBLIC KEY"; +}; /** A PKCS#8's armor is labelled `PRIVATE KEY`. */ template <> -inline constexpr std::string_view pem_label_v = "PRIVATE KEY"; +struct pem_label { + /** The label. */ + static constexpr std::string_view value = "PRIVATE KEY"; +}; /** * Whether `pem` takes `Inner`: an `formats::spki_t` or `formats::pkcs8_t`, the DER formats @@ -276,15 +286,19 @@ inline constexpr bool is_pem_inner_v = true; namespace formats { /** - * The type of `formats::pem(inner)`: codecs' armor over `Inner` (design R23). + * The type of `formats::pem(inner)`: codecs' armor whose label is in its type, over `Inner` + * (design D3, codecs' D11). * - * The armor is configured with `Inner`'s label. The links are the chain's members `outer`, the - * armor, and `inner`. + * The label is `Inner`'s, `detail::pem_label::value`: `PUBLIC KEY` for `spki_t` and + * `PRIVATE KEY` for `pkcs8_t`, so that no value of the type holds another, and every verb writes + * and reads that label. The links are the chain's members `outer`, the armor, and `inner`. Its + * default result is exactly as long as the armor of the inner pair's `max_encoded_size` bytes with + * that label (codecs' R24). * * @tparam Inner The DER format inside the armor, `spki_t` or `pkcs8_t`. */ template -using pem_t = codecs::over; +using pem_t = codecs::over>, Inner>; /** * The type of @ref pem, which makes the PEM format of a DER format of a key. @@ -296,25 +310,29 @@ struct pem_builder_t { explicit pem_builder_t() = default; /** - * The PEM of `inner`: codecs' `formats::armor` with `inner`'s label over `inner`. + * The PEM of `inner`: codecs' `formats::basic_armor` with `inner`'s label in its type, over + * `inner`, a `pem_t`. * * The label is `PUBLIC KEY` for `spki` (any point form) and `PRIVATE KEY` for `pkcs8`: no * function of crypto takes a label from its caller. Any other `inner`, `raw` or `der`, stops - * the build. + * the build, with that error alone. * * @tparam Inner The inner format's type. * @param inner The inner format. * @return The PEM format. */ template - [[nodiscard]] constexpr pem_t operator()(Inner inner) const noexcept { + [[nodiscard]] constexpr auto operator()(Inner inner) const noexcept { static_assert(detail::is_pem_inner_v, "webcpp::crypto: PEM carries a DER key: pem(formats::spki) or " "pem(formats::pkcs8)"); if constexpr (detail::is_pem_inner_v) { - return pem_t{codecs::formats::armor(detail::pem_label_v), inner}; + return pem_t{codecs::formats::basic_armor>{}, inner}; } else { - return pem_t{codecs::formats::armor, inner}; + // Never a program's: the assertion above stops the build. The armor without a label + // names no pem_label of `Inner`, which has none, so that the assertion is the build's + // only error. + return codecs::over{codecs::formats::armor, inner}; } } }; @@ -356,21 +374,13 @@ inline constexpr std::size_t max_decode_input_size = namespace detail { /** - * A list of formats: crypto's own, `all_formats`, and each value type's, `formats_of`. - * - * @tparam Formats The formats, each a format of the base form. - */ -template -struct format_list {}; - -/** - * The library's one list of formats (design D1): the formats of keys and signatures, each of its - * base form, from which `is_format_v`, the check of every pair, the tests and the guide's table - * derive. A later format (JWK) is one more entry. + * The library's one list of formats (design D1), a `codecs::format_list`: the formats of keys and + * signatures, each of its base form, from which `is_format_v`, crypto's declaration of every type + * to codecs, the tests and the guide's table derive. A later format (JWK) is one more entry. */ using all_formats = - format_list, formats::spki_t<>, formats::pkcs8_t, formats::der_t, - formats::pem_t>, formats::pem_t>; + codecs::format_list, formats::spki_t<>, formats::pkcs8_t, formats::der_t, + formats::pem_t>, formats::pem_t>; /** * A list of point forms: the ones a value type accepts for a format, `forms_of`. @@ -381,7 +391,7 @@ template struct form_list {}; /** - * Whether `Item` is one of a `format_list`'s formats or a `form_list`'s forms. + * Whether `Item` is one of a `codecs::format_list`'s formats or a `form_list`'s forms. * * @tparam Item The type to look for. * @tparam List The list. @@ -391,7 +401,7 @@ inline constexpr bool in_list_v = false; /** A format is in a list of formats when it is one of them. */ template -inline constexpr bool in_list_v> = +inline constexpr bool in_list_v> = (std::is_same_v || ...); /** A form is in a list of forms when it is one of them. */ @@ -504,20 +514,21 @@ inline constexpr bool is_format_v = in_list_v, all_formats * Whether every format of `List` is one of `all_formats`: what a curve's formats header asserts * beside each `formats_of` it declares (design D1). * - * @tparam List A `format_list`. + * @tparam List A `codecs::format_list`. */ template inline constexpr bool known_formats_v = false; /** A list of formats is known when each of its formats is in `all_formats`. */ template -inline constexpr bool known_formats_v> = +inline constexpr bool known_formats_v> = (in_list_v && ...); /** - * The formats a value type of crypto's has: a `format_list` of formats of `all_formats`, declared - * by the type's curve's `formats.hpp`, in one place beside its value codecs; `void` for a type - * whose formats header is not included. + * The formats a value type of crypto's has: a `codecs::format_list` of formats of `all_formats`, + * declared by the type's curve's `formats.hpp`, in one place beside its value codecs; `void` for a + * type whose formats header is not included. crypto's declaration to codecs states it as the type's + * `formats`. * * @tparam T The value's type. */ @@ -541,8 +552,8 @@ using formats_of_t = formats_of::type; * * A specialization lists `formats::default_form_t` among its forms: a format named without a * point form names it, and every pair of design D4 has its default form (the uncompressed point, - * or the x-only key's own 32 bytes). The verbs' check stops the build on a list without it, before - * the type's list is read. + * or the x-only key's own 32 bytes). crypto's declaration stops the build on a list without it, + * before the type's list is read. * * @tparam Format The base form of a format. * @tparam T The value's type. @@ -564,21 +575,21 @@ using forms_of_t = forms_of::type; /** * Whether the value type `T`, whose formats are `List`, refuses `Format`: the base form of - * `Format` is not in `List`, or the point form it names is not in `forms_of`. Its template - * arguments, the type's list among them, are what a compiler prints in the failed requirement of - * crypto's check (design D3); false for a type that declares no list. + * `Format` is not in `List`, or the point form it names is not in `forms_of`. crypto's declaration + * to codecs states the type's `has_format` as its negation (design D2); false for a type that + * declares no list. * * @tparam Format The format's type. * @tparam T The value's type. - * @tparam List The type's `format_list`. + * @tparam List The type's `codecs::format_list`. */ template inline constexpr bool format_refused = false; /** Refused when the base form is not listed, or the point form is not accepted. */ template -inline constexpr bool format_refused> = - !in_list_v, format_list> || +inline constexpr bool format_refused> = + !in_list_v, codecs::format_list> || !in_list_v::type, forms_of_t::type, T>>; @@ -591,7 +602,8 @@ template inline constexpr bool formats_declared_v = !std::is_void_v>; /** - * A pair's own reason for its refusal, which adds a fixed sentence to crypto's check (design D3). + * A pair's own reason for its refusal, whose fixed sentence crypto's declaration gives codecs + * (design D2, `formats`' D3). */ enum class refusal_reason : unsigned char { /** No reason of its own: the type's list says it. */ @@ -617,8 +629,8 @@ template inline constexpr refusal_reason refusal_reason_v = refusal_reason::none; /** - * The reason a curve gives for refusing `Format` on `T` when decoding alone, consulted by - * `crypto::decode` before `refusal_reason_v` (an encode-only pair, as `raw(xonly)` of a + * The reason a curve gives for refusing `Format` on `T` when decoding alone, consulted by crypto's + * declaration before `refusal_reason_v` (an encode-only pair, as `raw(xonly)` of a * `curves::secp256k1::public_key`); `none` unless the curve's formats header specializes it. * * @tparam Format The format's type. @@ -680,17 +692,6 @@ consteval bool check_bounds() noexcept { return bytes.size(); } -/** - * Whether crypto checks a call of `Format` on `Value`: `Value` is a type of crypto's and `Format` - * a format of crypto's. Any other pair is codecs' to check. - * - * @tparam Format The format's type. - * @tparam Value The value's type. - */ -template -inline constexpr bool checked_by_crypto_v = - curve_of_v != curve_id::none && is_format_v; - /** * Whether `T`'s `forms_of` for `Format` lists `formats::default_form_t`, as every specialization * must (a format named without a point form names it). @@ -703,32 +704,44 @@ inline constexpr bool default_form_listed_v = in_list_v::type, T>>; /** - * Whether the pair passes crypto's check, in the direction `Decoding` says: always for a pair - * crypto does not check; else the type's formats are declared, the pair has no reason of its own, - * its list holds the format and its form, and codecs converts it. + * Whether `Format` is an armor over a DER format of a key that is not `formats::pem_t` of that + * format (design D2's fifth reason, R5): codecs' `armor_t`, with any label, or a `basic_armor` + * whose label is not the inner format's, over `formats::spki_t` or `formats::pkcs8_t`. A + * key's PEM is `formats::pem(inner)`, whose label is in its type. An armor over `raw` or `der` is + * a composition, as `codecs::over{codecs::formats::base64, inner}` is, and no reason of crypto's. * - * @tparam Decoding Whether the call decodes. * @tparam Format The format's type. - * @tparam Value The value's type. - * @return Whether the call may proceed to codecs. - */ -template -consteval bool pair_accepted() noexcept { - if constexpr (!checked_by_crypto_v) { - return true; - } else if constexpr (Decoding) { - return formats_declared_v && default_form_listed_v && - decode_refusal_reason_v == refusal_reason::none && - refusal_reason_v == refusal_reason::none && - !format_refused> && - codecs::decodable; - } else { - return formats_declared_v && default_form_listed_v && - refusal_reason_v == refusal_reason::none && - !format_refused> && - codecs::encodable; - } -} + */ +template +inline constexpr bool other_armor_v = false; + +/** codecs' armor over a DER format of a key, whatever its label. */ +template +inline constexpr bool other_armor_v> = + is_pem_inner_v; + +/** codecs' armor with its label in its type over a DER format of a key, the label not its own. */ +template +inline constexpr bool + other_armor_v, Inner, Allocator>> = + is_pem_inner_v && !std::is_same_v>; + +/** + * Whether `T` refuses `Format` for a reason of crypto's, in the direction `Decoding` says: what + * crypto's declaration to codecs states as `has_reason` (design D2), in its order. The type's + * formats header is not included; its `forms_of` for the format lacks the default form; decoding, + * the pair's reason of decoding alone; the pair's reason of both directions; or the format is an + * armor over a DER format of a key other than `formats::pem_t` of it. + * + * @tparam Decoding Whether the conversion decodes. + * @tparam Format The format's type. + * @tparam T The value's type. + */ +template +inline constexpr bool refused_for_reason_v = + !formats_declared_v || !default_form_listed_v || + (Decoding && decode_refusal_reason_v != refusal_reason::none) || + refusal_reason_v != refusal_reason::none || other_armor_v; /** * Stops the build with the sentence of `Reason` (design D3). @@ -751,58 +764,49 @@ constexpr void refuse_for_reason() noexcept { } /** - * Stops the build for a pair `pair_accepted` refuses, with the first of crypto's sentences that - * applies (design D3): the formats header to include; a `forms_of` without the default form; the - * pair's own reason; that the type has no such format, the type's list printed in the failed - * requirement; or that codecs does not convert the pair in this direction. + * Stops the build for a pair `refused_for_reason_v` holds for, with the first of crypto's + * sentences that applies (design D2): the formats header to include; a `forms_of` without the + * default form; the pair's reason when decoding, then in both directions; or that a key's PEM is + * `formats::pem(formats::spki)` or `formats::pem(formats::pkcs8)`. What crypto's declaration to + * codecs states as `refuse`, which codecs calls in place of converting. * - * @tparam Decoding Whether the call decodes. + * @tparam Decoding Whether the conversion decodes. * @tparam Format The format's type. - * @tparam Value The value's type. + * @tparam T The value's type. */ -template -constexpr void refuse_pair() noexcept { - if constexpr (!formats_declared_v) { - static_assert(curve_of_v != curve_id::ed25519 || formats_declared_v, +template +constexpr void refuse_with_sentence() noexcept { + if constexpr (!formats_declared_v) { + static_assert(curve_of_v != curve_id::ed25519 || formats_declared_v, "webcpp::crypto: include to " "encode or decode this type"); - static_assert(curve_of_v != curve_id::x25519 || formats_declared_v, + static_assert(curve_of_v != curve_id::x25519 || formats_declared_v, "webcpp::crypto: include to " "encode or decode this type"); - static_assert(curve_of_v != curve_id::p256 || formats_declared_v, + static_assert(curve_of_v != curve_id::p256 || formats_declared_v, "webcpp::crypto: include to encode " "or decode this type"); - static_assert(curve_of_v != curve_id::secp256k1 || formats_declared_v, + static_assert(curve_of_v != curve_id::secp256k1 || formats_declared_v, "webcpp::crypto: include to " "encode or decode this type"); - } else if constexpr (!default_form_listed_v) { - static_assert(default_form_listed_v, + } else if constexpr (!default_form_listed_v) { + static_assert(default_form_listed_v, "webcpp::crypto: a forms_of specialization lists formats::default_form_t, " "the form of a format named without one"); - } else if constexpr (Decoding && - decode_refusal_reason_v != refusal_reason::none) { - refuse_for_reason>(); - } else if constexpr (refusal_reason_v != refusal_reason::none) { - refuse_for_reason>(); - } else if constexpr (format_refused>) { - // Qualified, so that the failed requirement names the trait and the type's list. - static_assert(!webcpp::crypto::detail::format_refused>, - "webcpp::crypto: this type has no such format; the formats it has are the " - "format_list named in this assertion"); - } else if constexpr (Decoding) { - static_assert(codecs::decodable, - "webcpp::crypto: this type lists the format, and no codecs::value_codec of " - "the pair decodes it"); + } else if constexpr (Decoding && decode_refusal_reason_v != refusal_reason::none) { + refuse_for_reason>(); + } else if constexpr (refusal_reason_v != refusal_reason::none) { + refuse_for_reason>(); } else { - static_assert(codecs::encodable, - "webcpp::crypto: this type lists the format, and no codecs::value_codec of " - "the pair encodes it"); + static_assert(!other_armor_v, + "webcpp::crypto: a key's PEM is formats::pem(formats::spki) or " + "formats::pem(formats::pkcs8), whose label is the inner format's"); } } /** - * Whether `crypto::encode` of the pair, with `Rest`, cannot throw: codecs' verb's own answer for a - * pair that passes the check (a pair of crypto's is `noexcept`). + * Whether `codecs::encode` of `Value` in `Format`, with `Rest`, cannot throw: codecs' verb's own + * answer, which each member `encode` gives (design D1). * * @tparam Format The format's type. * @tparam Value The value's type. @@ -811,56 +815,14 @@ constexpr void refuse_pair() noexcept { */ template consteval bool encode_is_noexcept() { - if constexpr (pair_accepted()) { - return noexcept(codecs::encode(std::declval(), std::declval(), - std::declval()...)); - } else { - return true; - } + return noexcept(codecs::encode(std::declval(), std::declval(), + std::declval()...)); } /** - * Whether a call of `Format` on `Value` runs with the inner format's fixed label (owner decision - * 1, "the label can never be wrong"): `Format` is a PEM and the pair is crypto's. A hand-built - * `formats::pem_t` whose armor holds another label, or none, encodes and decodes with - * `pem_label_v` all the same; any other pair keeps its own armor. - * - * @tparam Format The format's type. - * @tparam Value The value's type. - */ -template -inline constexpr bool fixes_pem_label_v = false; - -/** A PEM of crypto's pair has its inner format's label. */ -template -inline constexpr bool fixes_pem_label_v, Value> = - checked_by_crypto_v, Value>; - -/** - * The armor a PEM call of `Value` in `format` runs: codecs' armor with `pem_label_v` for a - * pair of crypto's (`fixes_pem_label_v`), whatever armor `format` holds; `format`'s own for any - * other pair. - * - * @tparam Value The value's type. - * @tparam Inner The DER format inside the armor. - * @param format The PEM format. - * @return The armor. - */ -template -[[nodiscard]] constexpr codecs::formats::armor_t pem_armor_of( - formats::pem_t const& format) noexcept { - if constexpr (fixes_pem_label_v, Value>) { - return codecs::formats::armor(pem_label_v); - } else { - return format.outer; - } -} - -/** - * Whether `crypto::decode` of `Input` in `Format` cannot throw: codecs' verb's answer for a - * pair that passes crypto's check, a PEM of crypto's pair through the format with its inner - * format's label (the same type); `noexcept` for every pair of crypto's but a key pair whose decode - * allocates from a memory resource (secp256k1's signing context). + * Whether `codecs::decode` of `Input` in `Format` cannot throw: codecs' verb's own answer, + * which each member `decode` gives (design D1); `noexcept` for every pair of crypto's but a key + * pair whose decode allocates from a memory resource (secp256k1's signing context). * * @tparam Value The value's type. * @tparam Format The format's type. @@ -869,31 +831,83 @@ template */ template consteval bool decode_is_noexcept() { - if constexpr (pair_accepted()) { - return noexcept( - codecs::decode(std::declval(), std::declval())); - } else { - return true; - } + return noexcept( + codecs::decode(std::declval(), std::declval())); } } // namespace detail +} // namespace webcpp::crypto + +namespace webcpp::codecs { + /** - * Encodes `value` in `format`: checks the pair against crypto's list, then returns - * `codecs::encode(format, value, rest...)` (design R18), codecs' default result (`bytes`, - * `text`, `secret_bytes`, `secret_text`, `N` the value codec's `max_encoded_size`), the - * result of a token of codecs' (`codecs::tokens::append_to(text)`), or, into a caller's - * `std::span` or `std::span`, the size written. + * crypto's declaration of every one of its value types to codecs (design D2, codecs' D9): each type + * whose `crypto::detail::curve_of_v` names a curve, its formats header included or not, so that + * `codecs::encode`, `codecs::decode`, `codecs::encodable`, `codecs::decodable`, + * `codecs::check_conversion` and the members convert exactly crypto's pairs and refuse any other + * with one error. + * + * Its `formats` is the type's `crypto::detail::formats_of_t`, `codecs::format_list<>` for a type + * whose formats header is not included; `has_format` holds when the format's base form is + * listed and its point form accepted (`crypto::detail::format_refused`, negated); `has_reason` and + * `refuse` are crypto's reasons, in the order of design D2: the formats header to include, a + * `forms_of` without the default form, the pair's reason of decoding, its reason of both + * directions, and an armor over `spki` or `pkcs8` other than `crypto::formats::pem` of it. Each + * reason stops the build with crypto's sentence, reported in this header; a format the type does + * not have is refused with codecs' message that names the type's `codecs::format_list`, and a + * listed pair with no value codec with codecs' message, both in codecs' header. A composition of a + * format of the type under another codec, `codecs::over{codecs::formats::base64, + * crypto::formats::spki}`, converts as its inner format does. * - * For a type of crypto's and a format of crypto's, the build stops when the type's curve's formats - * header is not included, when the pair has a reason of its own (an Ed25519 signature has no DER - * form), when the type's list lacks the format or its point form (the list printed in the failed - * requirement), or when no value codec encodes the pair. A PEM of crypto's pair is written with - * its inner format's label, `PUBLIC KEY` or `PRIVATE KEY`, whatever armor a hand-built - * `formats::pem_t` holds. Any other pair is passed to codecs untouched. The span form refuses an - * output shorter than the exact encoding with `codecs::error::output_too_small` and writes nothing - * on any error (design R34). + * @tparam T The value's type. + */ +template + requires(crypto::detail::curve_of_v != crypto::detail::curve_id::none) +struct value_formats { + /** The type's formats, or none when its formats header is not included. */ + using formats = std::conditional_t, + crypto::detail::formats_of_t, format_list<>>; + + /** + * Whether the type has `Format`: its base form is listed, and its point form accepted. + * + * @tparam Format The format's type. + */ + template + static constexpr bool has_format = + crypto::detail::formats_declared_v && + !crypto::detail::format_refused>; + + /** + * Whether the pair of `Format` has a reason of crypto's in `Direction`. + * + * @tparam Format The format's type. + * @tparam Direction The direction of the conversion. + */ + template + static constexpr bool has_reason = + crypto::detail::refused_for_reason_v; + + /** + * Stops the build with crypto's sentence for the pair's reason in `Direction`. + * + * @tparam Format The format's type. + * @tparam Direction The direction of the conversion. + */ + template + static constexpr void refuse() noexcept { + crypto::detail::refuse_with_sentence(); + } +}; + +} // namespace webcpp::codecs + +namespace webcpp::crypto { + +/** + * `codecs::encode(format, value, rest...)`: a forward to codecs' verb, which is crypto's (design + * D1), removed in a later step of this change. * * @tparam Format The format's type. * @tparam Value The value's type. @@ -901,60 +915,29 @@ consteval bool decode_is_noexcept() { * @param format The format. * @param value The value. * @param rest Nothing, a token of codecs', or the caller's output. - * @return The encoding, or the error. + * @return What `codecs::encode(format, value, rest...)` returns. */ template [[nodiscard]] auto encode(Format const& format, Value const& value, Rest&&... rest) noexcept( detail::encode_is_noexcept()) { - if constexpr (!detail::pair_accepted()) { - detail::refuse_pair(); - return codecs::result{std::size_t{0}}; - } else if constexpr (detail::fixes_pem_label_v) { - return codecs::encode(Format{detail::pem_armor_of(format), format.inner}, value, - std::forward(rest)...); - } else { - return codecs::encode(format, value, std::forward(rest)...); - } + return codecs::encode(format, value, std::forward(rest)...); } /** - * Decodes `input` in `format` into a `Value`: checks the pair against crypto's list, as `encode` - * does, then returns `codecs::decode(format, input)` (design R18), a PEM of crypto's pair - * with its inner format's label. - * - * `input` is a `std::span` (or any byte input) for a binary format and a - * `std::string_view` (or any text) for a PEM, as the value codec's output kind says (design R4). - * An input longer than the pair's decode bound, `formats::max_decode_input_size`, is codecs' - * `codecs::error::input_too_long`, before the value codec reads a byte, directly and through PEM - * (codecs' owner decision 29). A PEM is decoded by codecs' `over`, in place: its DER held in an - * intermediate of the inner format's decode bound, never on the heap, wiped after a private - * format; the armor's errors are codecs' and come first (lines ended by a line feed or a carriage - * return and a line feed, the last ending optional, nothing before BEGIN or after END). A PEM of - * crypto's pair is read with its inner format's label, whatever armor a hand-built - * `formats::pem_t` holds: another label is codecs' `invalid_prefix`. `noexcept` on every pair of - * crypto's but a key pair whose decode allocates from a memory resource (secp256k1's signing - * context); a pair crypto does not check is as `codecs::decode` is, which allocates for a - * heap result. + * `codecs::decode(format, input)`: a forward to codecs' verb, which is crypto's (design + * D1), removed in a later step of this change. * * @tparam Value The value's type. * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The bytes, or the text. - * @return The value, or the error. + * @return What `codecs::decode(format, input)` returns. */ template -[[nodiscard]] codecs::result decode(Format const& format, Input const& input) noexcept( +[[nodiscard]] auto decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - if constexpr (!detail::pair_accepted()) { - detail::refuse_pair(); - return error::invalid_encoding; - } else if constexpr (detail::fixes_pem_label_v) { - return codecs::decode(Format{detail::pem_armor_of(format), format.inner}, - input); - } else { - return codecs::decode(format, input); - } + return codecs::decode(format, input); } } // namespace webcpp::crypto @@ -962,34 +945,34 @@ template namespace webcpp::crypto::detail { /** - * Encodes the signature in `format`: the member form of `crypto::encode`, which every signature + * Encodes the signature in `format`: the member form of `codecs::encode`, which every signature * type of crypto's declares (`detail/signature.hpp`). * * @tparam Format The format's type. * @param format The format. - * @return What `crypto::encode(format, *this)` returns. + * @return What `codecs::encode(format, *this)` returns. */ template template auto basic_signature::encode(Format const& format) const noexcept(detail::encode_is_noexcept()) { - return crypto::encode(format, *this); + return codecs::encode(format, *this); } /** - * Decodes a signature from `input` in `format`: the member form of `crypto::decode`. + * Decodes a signature from `input` in `format`: the member form of `codecs::decode`. * * @tparam Format The format's type. * @tparam Input The input's type. * @param format The format. * @param input The encoding. - * @return What `crypto::decode(format, input)` returns. + * @return What `codecs::decode(format, input)` returns. */ template template auto basic_signature::decode(Format const& format, Input const& input) noexcept( detail::decode_is_noexcept()) { - return crypto::decode(format, input); + return codecs::decode(format, input); } } // namespace webcpp::crypto::detail diff --git a/test/Jamfile b/test/Jamfile index d2a724da..1a9fc67c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -225,8 +225,10 @@ crypto-run formats_vocabulary : formats_vocabulary_test.cpp ; # gives one encoding, nothing on the heap, strict decoding, secret results # wiped when moved from, the two bounds and check_bounds, each pair's largest # valid input decoded and one byte more input_too_long on every path, a -# moved-from key pair refused, a type crypto does not own passed to codecs -# untouched; the wipes through secure's seam (support/wipe_record.hpp). +# moved-from key pair refused, crypto's declaration to codecs, the members as +# codecs' verbs in values, errors and noexcept, a type crypto does not own +# passed to codecs untouched and a format that is not crypto's refused on a +# crypto type; the wipes through secure's seam (support/wipe_record.hpp). crypto-run formats_verbs : formats_verbs_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # PEM over the toy through codecs' over, in place: the text OpenSSL writes, @@ -234,16 +236,19 @@ crypto-run formats_verbs : formats_verbs_test.cpp # crypto::decode, codecs::decode or the member, the armor's refusals, a payload # past the decode bound (an RSA key's) input_too_long as its DER is, codecs' # intermediate wiped after a pkcs8 and none made past the bound, codecs' guard -# held for a private format alone, the same values and errors on every path. +# held for a private format alone, the same values and errors on every path, +# each pair's label in its format's type, another label invalid_prefix. crypto-run formats_pem : formats_pem_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The room for JWK (design R17): a stand-in text format of the tests' own, -# added to a copy of the list, through crypto::encode and crypto::decode with -# no change to either. +# added to a copy of the list and to the list of a key of the tests' own, +# through codecs::encode and codecs::decode and crypto's declaration to codecs +# with no change to any of them; the toy key, whose list lacks it, refuses it. crypto-run formats_stand_in : formats_stand_in_test.cpp ; # The table of the valid pairs (design D4): every format of detail::all_formats -# with every point form over every type of the table, codecs' concepts and -# crypto's check agreeing, against doc/tables/crypto.json's formats section, +# with every point form over every type of the table, codecs' concepts, which +# crypto's declaration governs, and the compositions of each format, each PEM +# pair's exact capacity, against doc/tables/crypto.json's formats section, # read at run time from the directory WEBCPP_TEST_CRYPTO_TABLES gives (quoted, # with forward slashes, preopened on WASI), from which generate.py writes the # guide's table. diff --git a/test/formats_asynchronous_test.cpp b/test/formats_asynchronous_test.cpp index 733b1d31..b26f60db 100644 --- a/test/formats_asynchronous_test.cpp +++ b/test/formats_asynchronous_test.cpp @@ -8,7 +8,8 @@ // whose key pair takes an asynchronous backend, Ed25519, X25519 and P-256 (secp256k1's key pair has // none, ruling F26), a key pair of the stand-in backend (support/asynchronous_stand_in.hpp) has // no raw, no pkcs8 and no pem(pkcs8) value codec, codecs' own concepts saying so, and crypto's -// check refuses each with the reason that names WebCrypto's exportKey; its public key keeps raw, +// declaration to codecs refuses each, in both directions, with the reason that names WebCrypto's +// exportKey; its public key keeps raw, // spki and pem(spki), as on a synchronous backend. The messages are the message tests // pkcs8_on_asynchronous_ed25519, raw_on_asynchronous_x25519 and pkcs8_on_asynchronous_p256. // Everything here is checked at compile time: no key pair of the stand-in is made. @@ -37,10 +38,12 @@ using pem_spki_t = formats::pem_t>; /** Whether crypto refuses `Format` on `Value` for the reason D7 names, encoding and decoding. */ template constexpr bool refused_as_private_on_asynchronous() noexcept { + using declaration = codecs::value_formats; return detail::refusal_reason_v == detail::refusal_reason::private_on_asynchronous && - !detail::pair_accepted() && - !detail::pair_accepted(); + declaration::template has_reason && + declaration::template has_reason && + !codecs::encodable && !codecs::decodable; } /** @@ -66,10 +69,7 @@ constexpr bool private_formats_refused() noexcept { static_assert(codecs::encodable>); static_assert(codecs::encodable); static_assert(codecs::decodable>); - static_assert(detail::pair_accepted, public_key>()); - static_assert(detail::pair_accepted, public_key>()); - static_assert(detail::pair_accepted()); - static_assert(detail::pair_accepted()); + static_assert(codecs::decodable); return true; } diff --git a/test/formats_before_after_test.cpp b/test/formats_before_after_test.cpp index 3d14a651..4177a90d 100644 --- a/test/formats_before_after_test.cpp +++ b/test/formats_before_after_test.cpp @@ -6,8 +6,9 @@ // The guide's "Before and after" (design "Before and after"): the calls that replaced each // curve's format functions, crypto::pem, the scheme tags in crypto:: and the free low-S -// functions, on real keys, each result checked. The region `after` is what the guide shows; the -// two calls it names as refused are the message tests der_on_ed25519 and verify_secp256k1_any_s. +// functions, on real keys, each result checked; a value is encoded and decoded by codecs' verbs +// (one-verb's D1). The region `after` is what the guide shows; the two calls it names as refused +// are the message tests der_on_ed25519 and verify_secp256k1_any_s. #include #include @@ -104,7 +105,7 @@ void before_and_after() { auto const event_id = filled(0x44); auto const event_signature = writer.sign(schemes::schnorr, event_id).value(); auto const writer_key = - crypto::encode(formats::raw(formats::xonly), writer.public_key().value()); + codecs::encode(formats::raw(formats::xonly), writer.public_key().value()); std::span const bytes = writer_key.value().view(); auto const internal_key = writer.xonly_public_key().value(); auto const tap_tweak = filled(0x55); @@ -112,40 +113,40 @@ void before_and_after() { // tag::after[] // A P-256 public key to PEM. - auto const text = crypto::encode(formats::pem(formats::spki), public_key); // text->view() + auto const text = codecs::encode(formats::pem(formats::spki), public_key); // text->view() auto const same_text = public_key.encode(formats::pem(formats::spki)); // A key pair from PKCS#8 PEM. - auto const read = crypto::decode(formats::pem(formats::pkcs8), pem_text); + auto const read = codecs::decode(formats::pem(formats::pkcs8), pem_text); auto const same_read = p256::keypair::decode(formats::pem(formats::pkcs8), pem_text); // Sign, then DER; verify a WebCrypto peer's signature, whatever its S, then normalize it. auto const signature = key.sign(schemes::ecdsa_sha256, message); - auto const der = crypto::encode(formats::der, *signature); + auto const der = codecs::encode(formats::der, *signature); auto const ok = crypto::verify(schemes::ecdsa_sha256, policies::any_s, peer_signature, message, peer_key); auto const low = peer_signature.low_s(); // Refused at compile time, each with crypto's sentence: an Ed25519 signature has no DER - // (`crypto::encode(formats::der, ed25519_signature)`), and secp256k1's ECDSA takes + // (`codecs::encode(formats::der, ed25519_signature)`), and secp256k1's ECDSA takes // low_s_only alone (`crypto::verify(schemes::ecdsa_sha256, policies::any_s, ...)`). // A Nostr key in 32 bytes, its Schnorr signature, a Taproot tweak. auto const nostr_key = - crypto::decode(formats::raw(formats::xonly), bytes); + codecs::decode(formats::raw(formats::xonly), bytes); auto const valid = nostr_key->verify(schemes::schnorr, policies::canonical, event_signature, event_id); auto const output_key = internal_key.tweak_add(tap_tweak); // X25519 and the point forms, new. - auto const x = crypto::encode(formats::spki, *x25519_key.public_key()); - auto const small = crypto::encode(formats::raw(formats::compressed), p256_public_key); + auto const x = codecs::encode(formats::spki, *x25519_key.public_key()); + auto const small = codecs::encode(formats::raw(formats::compressed), p256_public_key); // A caller that manages memory, and a token of codecs'. std::array, p256::public_key>> out{}; - auto const written = crypto::encode(formats::spki, public_key, std::span(out)); + auto const written = codecs::encode(formats::spki, public_key, std::span(out)); std::string pem_string; - auto const appended = crypto::encode(formats::pem(formats::spki), public_key, + auto const appended = codecs::encode(formats::pem(formats::spki), public_key, codecs::tokens::append_to(pem_string)); // end::after[] diff --git a/test/formats_ed25519_sodium_test.cpp b/test/formats_ed25519_sodium_test.cpp index ebe66ffc..b6f067e4 100644 --- a/test/formats_ed25519_sodium_test.cpp +++ b/test/formats_ed25519_sodium_test.cpp @@ -151,8 +151,8 @@ void rfc8410_keys() { /** * Both bounds of every pair, through formats::max_encoded_size and formats::max_decode_input_size * (owner decision 23): equal today; the deferred PKCS#8 version 2 would make pkcs8's decode bound - * 83. The PEM results' capacity is codecs' bound of the armor over every label, their exact size - * RFC 7468's (design D4). + * 83. The PEM results' capacity is exact, the armor of the inner pair's longest encoding with its + * own label (one-verb's D3), RFC 7468's size (design D4). */ void bounds() { using ed25519::public_key; @@ -168,22 +168,22 @@ void bounds() { static_assert(formats::max_decode_input_size == 48); static_assert(formats::max_encoded_size, signature> == 64); static_assert(formats::max_decode_input_size, signature> == 64); - static_assert(formats::max_encoded_size>, public_key> == 221); - static_assert(formats::max_encoded_size, key_pair> == 225); + static_assert(formats::max_encoded_size>, public_key> == 113); + static_assert(formats::max_encoded_size, key_pair> == 119); // The results: public bytes and text, secret bytes and text. using spki_result = decltype(crypto::encode(formats::spki, std::declval())); static_assert(std::is_same_v>>); using public_pem_result = decltype(crypto::encode(formats::pem(formats::spki), std::declval())); - static_assert(std::is_same_v>>); + static_assert(std::is_same_v>>); using raw_result = decltype(crypto::encode(formats::raw, std::declval())); static_assert(std::is_same_v>>); using pkcs8_result = decltype(crypto::encode(formats::pkcs8, std::declval())); static_assert(std::is_same_v>>); using private_pem_result = decltype(crypto::encode(formats::pem(formats::pkcs8), std::declval())); - static_assert(std::is_same_v>>); + static_assert(std::is_same_v>>); auto const pair = key_pair::from_secret(test::from_hex(rfc8410_seed)); if (!BOOST_TEST(pair.has_value())) { @@ -202,14 +202,13 @@ void refused_pairs() { namespace detail = crypto::detail; static_assert(detail::refusal_reason_v == detail::refusal_reason::no_der_ed25519_bip340); - static_assert(!detail::pair_accepted()); - static_assert(!detail::pair_accepted()); - static_assert(detail::pair_accepted()); + static_assert(!codecs::encodable); + static_assert(!codecs::decodable); + static_assert(codecs::encodable); // The public key has no PKCS#8, the key pair no SPKI, the signature no PEM. - static_assert(!detail::pair_accepted()); - static_assert(!detail::pair_accepted, ed25519::keypair>()); - static_assert(!detail::pair_accepted, - ed25519::public_key>()); + static_assert(!codecs::encodable); + static_assert(!codecs::decodable>); + static_assert(!codecs::encodable>); } // Every pair has the members, so that support/format_checks.hpp never skips them, and they are @@ -481,8 +480,8 @@ void malformed_der() { /** * PEM as Windows and OpenSSL's tools write it (Review Focus 1): CRLF line ends and no final line * feed decode to the key, through codecs' armor; explanatory text before BEGIN, as `openssl pkey - * -text` prints it, is codecs' invalid_prefix, never a key; the other label is refused, and a - * hand-built pem_t reads and writes the inner format's label alone (support/format_checks.hpp). + * -text` prints it, is codecs' invalid_prefix, never a key; the other label is refused, and each + * PEM format reads and writes its inner format's label, in its type (support/format_checks.hpp). */ void pem_variants() { auto const expected = diff --git a/test/formats_pem_test.cpp b/test/formats_pem_test.cpp index 503ccd1b..058805b1 100644 --- a/test/formats_pem_test.cpp +++ b/test/formats_pem_test.cpp @@ -14,7 +14,10 @@ // 2", its bound, decodes and 17 bytes are input_too_long; codecs' intermediate of a pkcs8 is wiped, // the written bytes, under codecs' guard, and none is made past the bound; every text gives the // same value or the same error through crypto::decode, codecs::decode and the member; codecs' -// decode of every PEM pair of the toy is noexcept. +// decode of every PEM pair of the toy is noexcept. The label is in the format's type (one-verb's +// D3): every PEM pair through codecs::encode and the member writes its inner format's label, its +// default result exactly as long as its PEM, and a text under another label is codecs' +// invalid_prefix through every verb. // The timing seam is defined before any webcpp header reads secure's guard. #include "support/timing_seam.hpp" @@ -153,6 +156,51 @@ void encode_private() { crypto::test::check_secret_result(formats::pem(formats::pkcs8), key_pair); } +/** + * Each PEM pair writes its inner format's label through codecs::encode and the member, the label + * in the format's type, its default result exactly as long as its PEM (codecs' R24); a text under + * another label, the other key's among them, is codecs' invalid_prefix through crypto::decode, + * codecs::decode and the member. + */ +void labels_in_the_type() { + toy_key const key{key_bytes}; + auto const key_pair = toy_keypair::from_secret(secret_bytes); + auto const public_text = codecs::encode(formats::pem(formats::spki), key); + auto const public_member = key.encode(formats::pem(formats::spki)); + auto const private_text = codecs::encode(formats::pem(formats::pkcs8), key_pair); + auto const private_member = key_pair.encode(formats::pem(formats::pkcs8)); + if (!BOOST_TEST(public_text.has_value()) || !BOOST_TEST(public_member.has_value()) || + !BOOST_TEST(private_text.has_value()) || !BOOST_TEST(private_member.has_value())) { + return; + } + BOOST_TEST(public_text->view().starts_with("-----BEGIN PUBLIC KEY-----\n")); + BOOST_TEST(public_text->view().ends_with("-----END PUBLIC KEY-----\n")); + BOOST_TEST(public_member->view() == public_text->view()); + BOOST_TEST(private_text->view().starts_with("-----BEGIN PRIVATE KEY-----\n")); + BOOST_TEST(private_text->view().ends_with("-----END PRIVATE KEY-----\n")); + BOOST_TEST(private_member->view() == private_text->view()); + // The 12 bytes of each DER fill the exact capacity of its label's armor. + BOOST_TEST_EQ(public_text->size(), public_text->capacity()); + BOOST_TEST_EQ(private_text->size(), private_text->capacity()); + + auto const refused = [](auto const& decoded) { + return !decoded.has_value() && decoded.error() == codecs::error::invalid_prefix; + }; + for (std::string_view const other : {"CERTIFICATE", "EC PRIVATE KEY", "PRIVATE KEY"}) { + std::string const text = armored(other, key_spki); + BOOST_TEST(refused(crypto::decode(formats::pem(formats::spki), text))); + BOOST_TEST(refused(codecs::decode(formats::pem(formats::spki), text))); + BOOST_TEST(refused(toy_key::decode(formats::pem(formats::spki), text))); + } + for (std::string_view const other : {"CERTIFICATE", "EC PRIVATE KEY", "PUBLIC KEY"}) { + std::string const text = armored( + other, joined(std::array{0x30, 0x0a, 0x02, 0x00}, secret_bytes)); + BOOST_TEST(refused(crypto::decode(formats::pem(formats::pkcs8), text))); + BOOST_TEST(refused(codecs::decode(formats::pem(formats::pkcs8), text))); + BOOST_TEST(refused(toy_keypair::decode(formats::pem(formats::pkcs8), text))); + } +} + /** * The text OpenSSL's tools write, its CRLF form and one without the final line feed decode to the * key (Review Focus 1). @@ -469,6 +517,7 @@ void same_as_codecs() { int main() { encode_public(); encode_private(); + labels_in_the_type(); decode_variants(); decode_in_place(); armor_refusals(); diff --git a/test/formats_stand_in_test.cpp b/test/formats_stand_in_test.cpp index e9a7f9f6..649603a3 100644 --- a/test/formats_stand_in_test.cpp +++ b/test/formats_stand_in_test.cpp @@ -4,11 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The room for JWK (design D1, R17): a text format of the tests' own, the stand-in of -// support/formats_toy.hpp, added to a copy of the library's one list, goes through crypto::encode -// and crypto::decode, which give codecs' text result and take a std::string_view, with no change to -// either; over the toy key's list with the stand-in added, crypto's check accepts it and still -// refuses der, as it does on the toy key's own list. +// The room for JWK (design D1, R17; the spec's scenario "The room for JWK"): a text format of the +// tests' own, the stand-in of support/formats_toy.hpp, added to a copy of the library's one list +// and to the list of a key of the tests' own, toy_jwk_key (toy_key's list with the stand-in added, +// and the stand-in's value codec), goes through codecs::encode and codecs::decode, which give +// codecs' text result and take a std::string_view, through crypto's declaration of the type to +// codecs, with no change to any of them; over that list crypto's declaration has the stand-in and +// still refuses der, as it does on the toy key's own list. The toy key, whose list lacks the +// stand-in, refuses it (one-verb's R4). #include "support/formats_toy.hpp" @@ -31,6 +34,7 @@ namespace formats = webcpp::crypto::formats; namespace detail = webcpp::crypto::detail; using webcpp::crypto::test::all_formats_with_stand_in; using webcpp::crypto::test::stand_in_text_t; +using webcpp::crypto::test::toy_jwk_key; using webcpp::crypto::test::toy_key; namespace { @@ -42,51 +46,66 @@ using toy_key_formats_with_stand_in = // The copy holds the library's six formats and the stand-in; the library's own list is unchanged. static_assert( std::is_same_v, formats::spki_t<>, formats::pkcs8_t, + codecs::format_list, formats::spki_t<>, formats::pkcs8_t, formats::der_t, formats::pem_t>, formats::pem_t, stand_in_text_t>>); +// The JWK's toy key lists the toy key's formats and the stand-in, and crypto declares it to codecs. +static_assert(std::is_same_v, toy_key_formats_with_stand_in>); +static_assert( + std::is_same_v::formats, toy_key_formats_with_stand_in>); +static_assert(codecs::value_formats::has_format); +static_assert(!codecs::value_formats::has_format); static_assert(detail::in_list_v); static_assert(!detail::in_list_v); static_assert(!detail::is_format_v); -// crypto's check over the list with the stand-in: the stand-in is no refusal, der still is. +// crypto's list check over the list with the stand-in: the stand-in is no refusal, der still is. static_assert(!detail::format_refused); static_assert(detail::format_refused); static_assert(detail::format_refused>); static_assert(!detail::format_refused, toy_key, toy_key_formats_with_stand_in>); -// codecs' concepts and results take the stand-in as they take crypto's formats. +// codecs' concepts and results take the stand-in as they take crypto's formats; der stays refused. static_assert(codecs::format); -static_assert(codecs::encodable); -static_assert(codecs::decodable); -static_assert(formats::max_encoded_size == 16); -static_assert(formats::max_decode_input_size == 16); +static_assert(codecs::encodable); +static_assert(codecs::decodable); +static_assert(!codecs::encodable); +static_assert(formats::max_encoded_size == 16); +static_assert(formats::max_decode_input_size == 16); + +// The toy key's list lacks the stand-in: refused by its list (one-verb's R4). +static_assert(!codecs::encodable); +static_assert(!codecs::decodable); -/** The stand-in through crypto's verbs, which give codecs' text result and take a text. */ +/** The stand-in through codecs' verbs, which give codecs' text result and take a text. */ void through_the_verbs() { - toy_key const key{std::array{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; - auto const encoded = crypto::encode(webcpp::crypto::test::stand_in_text, key); + toy_jwk_key const key{ + std::array{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; + auto const encoded = codecs::encode(webcpp::crypto::test::stand_in_text, key); static_assert(std::is_same_v>); if (BOOST_TEST(encoded.has_value())) { BOOST_TEST(encoded->view() == std::string_view{"0102030405060708"}); } std::string appended = "jwk: "; - auto const token = crypto::encode(webcpp::crypto::test::stand_in_text, key, + auto const token = codecs::encode(webcpp::crypto::test::stand_in_text, key, codecs::tokens::append_to(appended)); BOOST_TEST(token.has_value()); BOOST_TEST_EQ(appended, std::string{"jwk: 0102030405060708"}); - auto const decoded = crypto::decode(webcpp::crypto::test::stand_in_text, - std::string_view{"0102030405060708"}); + auto const decoded = codecs::decode(webcpp::crypto::test::stand_in_text, + std::string_view{"0102030405060708"}); if (BOOST_TEST(decoded.has_value())) { BOOST_TEST(*decoded == key); } - BOOST_TEST(crypto::decode(webcpp::crypto::test::stand_in_text, - std::string_view{"010203040506070G"}) + BOOST_TEST(codecs::decode(webcpp::crypto::test::stand_in_text, + std::string_view{"010203040506070G"}) .error() == crypto::error::invalid_encoding); - BOOST_TEST(crypto::decode(webcpp::crypto::test::stand_in_text, - std::string_view{"01020304050607"}) + BOOST_TEST(codecs::decode(webcpp::crypto::test::stand_in_text, + std::string_view{"01020304050607"}) .error() == crypto::error::invalid_encoding); + BOOST_TEST(codecs::decode(webcpp::crypto::test::stand_in_text, + std::string_view{"0102030405060708a"}) + .error() == codecs::error::input_too_long); } } // namespace diff --git a/test/formats_table_test.cpp b/test/formats_table_test.cpp index 4eafe0a3..f983befc 100644 --- a/test/formats_table_test.cpp +++ b/test/formats_table_test.cpp @@ -6,21 +6,28 @@ // The table of the valid pairs (design D4; the spec's scenario "A list in one place"): every format // of detail::all_formats, each with every point form it takes, over every type of the table, -// through codecs' own concepts, codecs::encodable and codecs::decodable, and crypto's check, -// detail::pair_accepted, which agree on every pair; then against doc/tables/crypto.json's -// `formats` section, read at run time: its list is all_formats's, in its order, its types are -// these, in this order, and each type's pairs are exactly the ones it has, a pair marked -// `encode_only` having no decode, one marked `secret` giving codecs' secret results, and the size -// of each binary pair being its max_encoded_size (a range's last number for `der`). The guide's -// table, doc/generated/formats.adoc, is generate.py's from the same section, which refuses a list -// that is not formats.hpp's: the table, the list and the types cannot drift apart unseen. A sample -// of each type is encoded in each of its pairs, its size the cell's (DER's shortest, r and s of 1, -// its range's first number; a PEM's RFC 7468's count of its inner pair's). The -// key pairs are on a synchronous backend (BearSSL, libsodium, libsecp256k1): one whose keys live -// in WebCrypto has no private format (design D7, formats_asynchronous_test.cpp). It prints each -// type's pairs as it finds them. +// through codecs' own concepts, codecs::encodable and codecs::decodable, which crypto's +// declaration to codecs governs (one-verb's D2): a composition under base64 converts exactly as its +// inner format does, an armor over raw or der likewise (codecs' R20), codecs' armor_t over spki or +// pkcs8, and basic_armor of the other key's label, never (R5), and hex no type (R4); then against +// doc/tables/crypto.json's `formats` section, read at run time: its list is all_formats's, in its +// order, its types are these, in this order, and each type's pairs are exactly the ones it has, a +// pair marked `encode_only` having no decode, one marked `secret` giving codecs' secret results, +// and the size of each binary pair being its max_encoded_size (a range's last number for `der`). +// The guide's table, doc/generated/formats.adoc, is generate.py's from the same section, which +// refuses a list that is not formats.hpp's: the table, the list and the types cannot drift apart +// unseen. A sample of each type is encoded in each of its pairs, its size the cell's (DER's +// shortest, r and s of 1, its range's first number; a PEM's RFC 7468's count of its inner pair's). +// The key pairs are on a synchronous backend (BearSSL, libsodium, libsecp256k1): one whose keys +// live in WebCrypto has no private format (design D7, formats_asynchronous_test.cpp). It prints +// each type's pairs as it finds them. Each PEM pair's default result is exact (one-verb's D3, +// Review Focus 3), full for the pair's longest PEM, and formats::pem(F) is a pem_t whose armor's +// label is detail::pem_label::value. #include +#include +#include +#include #include #include #include @@ -128,13 +135,13 @@ struct spelling> { */ template struct variants_of { - using type = detail::format_list; + using type = codecs::format_list; }; /** The point forms of design D1, the default first. */ template