diff --git a/doc/api_ref/pubkey.rst b/doc/api_ref/pubkey.rst index 0dc6c405c39..2aa397dfc44 100644 --- a/doc/api_ref/pubkey.rst +++ b/doc/api_ref/pubkey.rst @@ -2472,6 +2472,13 @@ width defined by the corresponding parameter set. Choosing `XMSS-SHA2_10_256` for instance will use the SHA2-256 hash function to generate a tree of height ten. +Besides the secret, the private key encoding holds 1024 nodes from the upper +part of the tree, which avoids recomputing the tree when signing, at the cost of +between 24 and 64 KiB of encoding. Keys in the older encoding, which lacks this data, are +still accepted, but keys are always written in the new encoding. It uses a +different PKCS #8 algorithm identifier, which older versions of Botan do not +recognize. + .. _xmss_example: Code Example: XMSS @@ -2523,3 +2530,12 @@ and `draft-fluhrer-lms-more-parm-sets-11 under(msec) || sig_timer->under(msec)) { if(signature.empty() || sig_timer->under(msec)) { + if(sk->remaining_operations().value_or(1) == 0) { + // A stateful key ran out of signatures; continue with a new one + sig.reset(); + ver.reset(); + sk = Botan::create_private_key(alg, rng, param); + pk = sk->public_key(); + if(!one_shot) { + sig.emplace(make_signer()); + ver.emplace(make_verifier()); + } + } + /* Length here is kind of arbitrary, but 48 bytes fits into a single hash block so minimizes hashing overhead versus the PK op itself. diff --git a/src/lib/asn1/static_oids.cpp b/src/lib/asn1/static_oids.cpp index fdda8f2219e..2651fbff659 100644 --- a/src/lib/asn1/static_oids.cpp +++ b/src/lib/asn1/static_oids.cpp @@ -1,5 +1,5 @@ /* -* This file was automatically generated by ./src/scripts/dev_tools/gen_oids.py on 2026-09-28 +* This file was automatically generated by ./src/scripts/dev_tools/gen_oids.py on 2026-11-24 * All manual changes will be lost. Edit the script instead. * * Botan is released under the Simplified BSD License (see license.txt) @@ -624,7 +624,11 @@ std::optional OID_Map::lookup_static_oid(const OID& oid) { case 0xA0D66: return if_match(oid, {1, 3, 6, 1, 4, 1, 25258, 1, 8}, "XMSS-draft12"); case 0xA0D6B: - return if_match(oid, {1, 3, 6, 1, 4, 1, 25258, 1, 13}, "HSS-LMS-Private-Key"); + return if_match(oid, {1, 3, 6, 1, 4, 1, 25258, 1, 13}, "HSS-LMS-Private-Key-legacy"); + case 0xA0D71: + return if_match(oid, {1, 3, 6, 1, 4, 1, 25258, 1, 19}, "HSS-LMS-Private-Key"); + case 0xA0D72: + return if_match(oid, {1, 3, 6, 1, 4, 1, 25258, 1, 20}, "XMSS-Private-Key"); case 0xA0EE1: return if_match(oid, {1, 3, 6, 1, 4, 1, 25258, 3, 1}, "Serpent/CBC"); case 0xA0EE2: @@ -1117,6 +1121,8 @@ std::optional OID_Map::lookup_static_oid_name(std::string_view req) { return if_match(req, "ECDSA", {1, 2, 840, 10045, 2, 1}); case 0x6BD26: return if_match(req, "GOST.INN", {1, 2, 643, 3, 131, 1, 1}); + case 0x6C21B: + return if_match(req, "HSS-LMS-Private-Key-legacy", {1, 3, 6, 1, 4, 1, 25258, 1, 13}); case 0x6CB3B: return if_match(req, "Camellia-192/OCB", {1, 3, 6, 1, 4, 1, 25258, 3, 2, 7}); case 0x6E602: @@ -1252,7 +1258,7 @@ std::optional OID_Map::lookup_static_oid_name(std::string_view req) { case 0x8E0C1: return if_match(req, "X509v3.CertificatePolicies", {2, 5, 29, 32}); case 0x8E39A: - return if_match(req, "HSS-LMS-Private-Key", {1, 3, 6, 1, 4, 1, 25258, 1, 13}); + return if_match(req, "HSS-LMS-Private-Key", {1, 3, 6, 1, 4, 1, 25258, 1, 19}); case 0x8EC51: return if_match(req, "Kyber-768-r3", {1, 3, 6, 1, 4, 1, 25258, 1, 7, 2}); case 0x8F94A: @@ -1409,6 +1415,8 @@ std::optional OID_Map::lookup_static_oid_name(std::string_view req) { return if_match(req, "gost_512B", {1, 2, 643, 7, 1, 2, 1, 2, 2}); case 0xBA1D8: return if_match(req, "X520.StreetAddress", {2, 5, 4, 9}); + case 0xBC6A5: + return if_match(req, "XMSS-Private-Key", {1, 3, 6, 1, 4, 1, 25258, 1, 20}); case 0xBCB45: return if_match(req, "PKCS12.CRLBag", {1, 2, 840, 113549, 1, 12, 10, 1, 4}); case 0xBCC82: diff --git a/src/lib/pubkey/hss_lms/hss.cpp b/src/lib/pubkey/hss_lms/hss.cpp index 8b1daea69aa..f0dd0c83296 100644 --- a/src/lib/pubkey/hss_lms/hss.cpp +++ b/src/lib/pubkey/hss_lms/hss.cpp @@ -16,7 +16,9 @@ #include #include #include +#include #include +#include #include namespace Botan { @@ -55,23 +57,23 @@ constexpr bool is_supported_hash_function(std::string_view hash_name) { } /** - * Given an HSS index, i.e. the number of already created HSS signatures, return the lms leaf indices for - * the different LMS layers from root layer to bottom layer. + * Private key section holding the cached public data of one LMS tree */ -std::vector derive_lms_leaf_indices_from_hss_index(HSS_Sig_Idx hss_idx, - const HSS_LMS_Params& hss_params) { - std::vector q(hss_params.L().get()); - for(int32_t layer_ctr = hss_params.L().get() - 1; layer_ctr >= 0; --layer_ctr) { - HSS_Level layer(layer_ctr); - const HSS_LMS_Params::LMS_LMOTS_Params_Pair& layer_params = hss_params.params_at_level(layer); - const size_t layer_h = layer_params.lms_params().h(); - q.at(layer.get()) = - checked_cast_to(hss_idx.get() % checked_cast_to(1ULL << layer_h)); - hss_idx = hss_idx >> layer_h; - } - BOTAN_ARG_CHECK(hss_idx == HSS_Sig_Idx(0), "HSS Tree is exhausted"); +constexpr uint32_t HSS_SECTION_LMS_TREE = 1; - return q; +/** + * Size of an encoded HSS_SECTION_LMS_TREE body for the tree at @p level + */ +size_t encoded_tree_size(const HSS_LMS_Params& params, HSS_Level level) { + const auto& level_params = params.params_at_level(level); + size_t size = sizeof(uint32_t) + sizeof(uint64_t) + + Merkle_Treetop::row_size(level_params.lms_params().h(), level_params.lms_params().m()); + if(level > 0U) { + const auto& parent_params = params.params_at_level(level - 1); + size += LMS_Signature::size(parent_params.lms_params(), parent_params.lmots_params()); + size += LMS_PublicKey::size(level_params.lms_params()); + } + return size; } /** @@ -153,7 +155,8 @@ HSS_LMS_PrivateKeyInternal::HSS_LMS_PrivateKeyInternal(const HSS_LMS_Params& hss m_identifier(rng.random_vec(LMS_IDENTIFIER_LEN)), m_keyid( "HSS-LMS", hss_param_encoding(m_hss_params), m_hss_params.max_sig_count().get(), m_hss_seed, m_identifier), - m_sig_size(HSS_Signature::size(m_hss_params)) {} + m_sig_size(HSS_Signature::size(m_hss_params)), + m_cache(m_hss_params.L().get()) {} HSS_LMS_PrivateKeyInternal::HSS_LMS_PrivateKeyInternal(HSS_LMS_Params hss_params, LMS_Seed hss_seed, @@ -163,18 +166,20 @@ HSS_LMS_PrivateKeyInternal::HSS_LMS_PrivateKeyInternal(HSS_LMS_Params hss_params m_identifier(std::move(identifier)), m_keyid( "HSS-LMS", hss_param_encoding(m_hss_params), m_hss_params.max_sig_count().get(), m_hss_seed, m_identifier), - m_sig_size(HSS_Signature::size(m_hss_params)) { + m_sig_size(HSS_Signature::size(m_hss_params)), + m_cache(m_hss_params.L().get()) { BOTAN_ARG_CHECK(m_hss_seed.size() == m_hss_params.params_at_level(HSS_Level(0)).lms_params().m(), "Invalid HSS-LMS seed size"); BOTAN_ARG_CHECK(m_identifier.size() == LMS_IDENTIFIER_LEN, "Invalid HSS-LMS identifier size"); } std::shared_ptr HSS_LMS_PrivateKeyInternal::from_bytes_or_throw( - std::span key_bytes) { - if(key_bytes.size() < sizeof(HSS_Level) + sizeof(HSS_Sig_Idx)) { + std::span key_bytes, HSS_LMS_PrivateKey_Format format) { + BufferSlicer slicer(key_bytes); + + if(slicer.remaining() < sizeof(HSS_Level) + sizeof(HSS_Sig_Idx)) { throw Decoding_Error("Too few private key bytes."); } - BufferSlicer slicer(key_bytes); const auto L = load_be(slicer.take()); if(L == 0U || L > HSS_MAX_LEVELS) { @@ -205,36 +210,191 @@ std::shared_ptr HSS_LMS_PrivateKeyInternal::from_byt if(slicer.remaining() < params.at(0).lms_params().m() + LMS_IDENTIFIER_LEN) { throw Decoding_Error("Out of bytes while parsing private HSS-LMS key."); } - auto hss_seed = slicer.copy(params.at(0).lms_params().m()); + const size_t m = params.at(0).lms_params().m(); + auto hss_seed = slicer.copy(m); auto identifier = slicer.copy(LMS_IDENTIFIER_LEN); + HSS_LMS_Params hss_params(std::move(params)); + + // The legacy format consists of exactly the fields parsed so far + // TODO(Botan4) Remove the legacy format + const bool legacy = + (format == HSS_LMS_PrivateKey_Format::Legacy) || (format == HSS_LMS_PrivateKey_Format::Either && slicer.empty()); + + std::optional root; + std::vector encoded_trees; + + if(!legacy) { + const auto take = [](BufferSlicer& s, size_t count) { + if(s.remaining() < count) { + throw Decoding_Error("Out of bytes while parsing private HSS-LMS key."); + } + return s.take(count); + }; + const auto take_u32 = [&](BufferSlicer& s) { + return load_be(take(s, sizeof(uint32_t)).first()); + }; + const auto take_u64 = [&](BufferSlicer& s) { + return load_be(take(s, sizeof(uint64_t)).first()); + }; + + root = LMS_Tree_Node(take(slicer, m)); + + const auto section_count = take_u32(slicer); + for(uint32_t i = 0; i != section_count; ++i) { + const auto tag = take_u32(slicer); + const auto length = take_u32(slicer); + BufferSlicer body(take(slicer, length)); + + // Sections with unknown tags are skipped, to allow adding new ones later + if(tag != HSS_SECTION_LMS_TREE) { + continue; + } + + const HSS_Level level(take_u32(body)); + if(level >= hss_params.L()) { + throw Decoding_Error("Invalid level of cached LMS tree in private HSS-LMS key."); + } + if(!encoded_trees.empty() && level <= encoded_trees.back().level) { + throw Decoding_Error("Cached LMS trees in private HSS-LMS key are out of order."); + } + if(length != encoded_tree_size(hss_params, level)) { + throw Decoding_Error("Invalid size of cached LMS tree in private HSS-LMS key."); + } + + const auto tree_number = take_u64(body); + const auto& lms_params = hss_params.params_at_level(level).lms_params(); + const auto row = body.take(Merkle_Treetop::row_size(lms_params.h(), lms_params.m())); + const auto signed_pub_key = body.take(body.remaining()); + encoded_trees.push_back(Encoded_Tree{level, tree_number, row, signed_pub_key}); + } + } + if(!slicer.empty()) { throw Decoding_Error("Private HSS-LMS key contains more bytes than expected."); } auto sk = std::shared_ptr( - new HSS_LMS_PrivateKeyInternal(HSS_LMS_Params(std::move(params)), std::move(hss_seed), std::move(identifier))); + new HSS_LMS_PrivateKeyInternal(std::move(hss_params), std::move(hss_seed), std::move(identifier))); sk->set_idx(sig_idx); + + if(root.has_value()) { + sk->m_root = std::move(root); + sk->adopt_encoded_trees(sig_idx, encoded_trees); + } + return sk; } +void HSS_LMS_PrivateKeyInternal::adopt_encoded_trees(HSS_Sig_Idx idx, const std::vector& encoded) { + if(idx >= hss_params().max_sig_count()) { + return; + } + const auto pos = tree_position(idx); + + // Each tree is only kept if it is the one used for the next signature, and + // the trees above it were kept, which allows checking it against its parent. + std::optional parent_pub = top_lms_public_key(); + size_t accepted = 0; + + try { + for(const auto& tree : encoded) { + const auto level = tree.level; + if(level.get() != accepted || tree.tree_number != pos.tree_number.at(level.get())) { + return; + } + ++accepted; + + const auto& params = hss_params().params_at_level(level); + + if(level == 0U) { + auto treetop = lms_treetop_from_row(params.lms_params(), m_identifier, tree.row); + if(!std::ranges::equal(treetop.root(), m_root.value())) { + return; + } + m_cache.at(0).tree = std::make_shared(0, std::move(treetop), std::vector()); + continue; + } + + BufferSlicer slicer(tree.signed_pub_key); + const auto sig = LMS_Signature::from_bytes_or_throw(slicer); + auto pub = LMS_PublicKey::from_bytes_or_throw(slicer); + const auto pub_bytes = pub.to_bytes(); + + if(!slicer.empty() || pub.lms_params().algorithm_type() != params.lms_params().algorithm_type() || + pub.lmots_params().algorithm_type() != params.lmots_params().algorithm_type() || + sig.q() != pos.q.at(level.get() - 1) || !parent_pub->verify_signature(LMS_Message(pub_bytes), sig)) { + return; + } + + auto treetop = lms_treetop_from_row(params.lms_params(), pub.identifier(), tree.row); + const LMS_PublicKey treetop_pub( + params.lms_params(), params.lmots_params(), pub.identifier(), LMS_Tree_Node(treetop.root())); + if(treetop_pub.to_bytes() != pub_bytes) { + return; + } + + m_cache.at(level.get()).tree = std::make_shared( + tree.tree_number, + std::move(treetop), + std::vector(tree.signed_pub_key.begin(), tree.signed_pub_key.end())); + parent_pub = std::move(pub); + } + } catch(const Decoding_Error&) { + // An unparsable signature or public key; keep the trees accepted so far + } +} + secure_vector HSS_LMS_PrivateKeyInternal::to_bytes() const { - secure_vector sk_bytes(size()); - BufferStuffer stuffer(sk_bytes); + const auto top_root = root(); + + uint64_t current_index = 0; + Tree_Cache cached; + + { + const lock_guard_type lock(m_cache_mutex); + current_index = Stateful_Key_Index_Registry::global().current_index(m_keyid); + cached = m_cache; + } + + // Only the trees used by the next signature are worth saving + std::vector> trees; + if(current_index < hss_params().max_sig_count().get()) { + const auto pos = tree_position(HSS_Sig_Idx(current_index)); + for(size_t level = 0; level != cached.size(); ++level) { + const auto& tree = cached[level].tree; + if(tree == nullptr || tree->tree_number() != pos.tree_number[level]) { + break; + } + trees.push_back(tree); + } + } - const uint64_t current_index = Stateful_Key_Index_Registry::global().current_index(m_keyid); + secure_vector sk_bytes; + const auto append = [&](const auto& bytes) { sk_bytes.insert(sk_bytes.end(), bytes.begin(), bytes.end()); }; - stuffer.append(store_be(hss_params().L())); - stuffer.append(store_be(current_index)); + append(store_be(hss_params().L())); + append(store_be(current_index)); for(HSS_Level layer(1); layer <= hss_params().L(); ++layer) { const auto& params = hss_params().params_at_level(layer - 1); - stuffer.append(store_be(params.lms_params().algorithm_type())); - stuffer.append(store_be(params.lmots_params().algorithm_type())); + append(store_be(params.lms_params().algorithm_type())); + append(store_be(params.lmots_params().algorithm_type())); + } + append(m_hss_seed); + append(m_identifier); + append(top_root); + + append(store_be(checked_cast_to(trees.size()))); + for(uint32_t level = 0; level != trees.size(); ++level) { + const auto& tree = *trees[level]; + append(store_be(HSS_SECTION_LMS_TREE)); + append(store_be(checked_cast_to(encoded_tree_size(hss_params(), HSS_Level(level))))); + append(store_be(level)); + append(store_be(tree.tree_number())); + append(tree.treetop().row()); + append(tree.signed_pub_key()); } - stuffer.append(m_hss_seed); - stuffer.append(m_identifier); - BOTAN_ASSERT_NOMSG(stuffer.full()); return sk_bytes; } @@ -259,56 +419,245 @@ HSS_Sig_Idx HSS_LMS_PrivateKeyInternal::reserve_next_idx() const { return HSS_Sig_Idx(idx.value()); } -size_t HSS_LMS_PrivateKeyInternal::size() const { - size_t sk_size = sizeof(HSS_Level) + sizeof(HSS_Sig_Idx); - // The concatenated algorithm types for all layers - sk_size += hss_params().L().get() * (sizeof(LMS_Algorithm_Type) + sizeof(LMOTS_Algorithm_Type)); - sk_size += m_hss_seed.size() + m_identifier.size(); - return sk_size; +HSS_LMS_PrivateKeyInternal::Tree_Position HSS_LMS_PrivateKeyInternal::tree_position(HSS_Sig_Idx idx) const { + const size_t L = hss_params().L().get(); + Tree_Position pos{std::vector(L), std::vector(L)}; + + uint64_t remaining = idx.get(); + for(size_t level = L; level-- > 0;) { + const uint32_t h = hss_params().params_at_level(HSS_Level(static_cast(level))).lms_params().h(); + pos.q[level] = LMS_Tree_Node_Idx(static_cast(remaining & ((uint64_t(1) << h) - 1))); + remaining >>= h; + pos.tree_number[level] = remaining; + } + BOTAN_ARG_CHECK(remaining == 0, "HSS Tree is exhausted"); + + return pos; +} + +std::vector HSS_LMS_PrivateKeyInternal::derive_lms_private_keys(const Tree_Position& pos) const { + std::vector sks; + sks.push_back(hss_derive_root_lms_private_key()); + for(HSS_Level level(1); level < hss_params().L(); ++level) { + sks.push_back( + hss_derive_child_lms_private_key(hss_params().params_at_level(level), sks.back(), pos.q.at(level.get() - 1))); + } + return sks; +} + +bool HSS_LMS_PrivateKeyInternal::ensure_subtree(Tree_Cache& cache, + HSS_Level level, + const Tree_Position& pos, + const LMS_PrivateKey& sk) const { + const uint32_t k = Merkle_Treetop::subtree_height(hss_params().params_at_level(level).lms_params().h()); + if(k == 0) { + // The treetop is the whole tree + return true; + } + + const auto& tree = cache.at(level.get()).tree; + BOTAN_ASSERT_NONNULL(tree); + const auto q = pos.q.at(level.get()); + + auto& slot = cache.at(level.get()).subtree; + if(slot != nullptr && slot->tree_number() == tree->tree_number() && slot->subtree().index() == (q.get() >> k)) { + return true; + } + + auto subtree = sk.build_subtree(tree->treetop(), q); + if(!subtree.has_value()) { + return false; + } + slot = std::make_shared(tree->tree_number(), std::move(subtree.value())); + return true; +} + +bool HSS_LMS_PrivateKeyInternal::ensure_tree(Tree_Cache& cache, + HSS_Level level, + const Tree_Position& pos, + const std::vector& sks) const { + const auto tree_number = pos.tree_number.at(level.get()); + auto& slot = cache.at(level.get()).tree; + if(slot != nullptr && slot->tree_number() == tree_number) { + return true; + } + + const auto& sk = sks.at(level.get()); + auto [treetop, subtree] = sk.build_tree(pos.q.at(level.get())); + + std::vector signed_pub_key; + if(level == 0U) { + set_root(LMS_Tree_Node(treetop.root())); + } else { + // The parent signs the public key just computed from the seed, never + // one taken from the cache. Since LM-OTS signing is deterministic, + // signing it again after the cache was lost reproduces the same + // signature instead of reusing the one-time key for another message. + const HSS_Level parent(level - 1); + if(!ensure_subtree(cache, parent, pos, sks.at(parent.get()))) { + return false; + } + + const auto& params = hss_params().params_at_level(level); + const auto& parent_params = hss_params().params_at_level(parent); + const auto pub_bytes = + LMS_PublicKey(params.lms_params(), params.lmots_params(), sk.identifier(), LMS_Tree_Node(treetop.root())) + .to_bytes(); + + const auto& parent_subtree = cache.at(parent.get()).subtree; + + LMS_Signature_Bytes parent_sig(LMS_Signature::size(parent_params.lms_params(), parent_params.lmots_params())); + sks.at(parent.get()) + .sign_with_nodes(parent_sig, + pos.q.at(parent.get()), + LMS_Message(pub_bytes), + cache.at(parent.get()).tree->treetop(), + (parent_subtree != nullptr) ? &parent_subtree->subtree() : nullptr); + CT::unpoison(parent_sig); + + signed_pub_key = concat>(parent_sig, pub_bytes); + } + + slot = std::make_shared(tree_number, std::move(treetop), std::move(signed_pub_key)); + cache.at(level.get()).subtree = std::make_shared(tree_number, std::move(subtree)); + return true; +} + +bool HSS_LMS_PrivateKeyInternal::populate_cache(Tree_Cache& cache, + const Tree_Position& pos, + const std::vector& sks) const { + // Top down, since building a tree requires a signature by its parent + for(HSS_Level level(0); level < hss_params().L(); ++level) { + if(!ensure_tree(cache, level, pos, sks)) { + return false; + } + } + const HSS_Level bottom(hss_params().L() - 1); + return ensure_subtree(cache, bottom, pos, sks.at(bottom.get())); +} + +void HSS_LMS_PrivateKeyInternal::update_cache(const Tree_Cache& cached, const Tree_Cache& updated) const { + const auto same_trees = [](const Cached_Level& a, const Cached_Level& b) { + return a.tree == b.tree && a.subtree == b.subtree; + }; + + const lock_guard_type lock(m_cache_mutex); + if(std::ranges::equal(m_cache, cached, same_trees)) { + m_cache = updated; + } +} + +void HSS_LMS_PrivateKeyInternal::set_root(const LMS_Tree_Node& root) const { + const lock_guard_type lock(m_cache_mutex); + if(m_root.has_value() && !std::ranges::equal(m_root.value(), root)) { + throw Invalid_State("HSS-LMS private key does not match its public key"); + } + m_root = root; +} + +LMS_Tree_Node HSS_LMS_PrivateKeyInternal::root() const { + uint64_t idx = 0; + Tree_Cache cached; + + { + const lock_guard_type lock(m_cache_mutex); + if(m_root.has_value()) { + return m_root.value(); + } + idx = Stateful_Key_Index_Registry::global().current_index(m_keyid); + cached = m_cache; + } + + // Compute the top tree, keeping the subtree used by the next signature + const auto pos = tree_position(HSS_Sig_Idx(idx < hss_params().max_sig_count().get() ? idx : 0)); + const auto sks = derive_lms_private_keys(pos); + + auto trees = cached; + ensure_tree(trees, HSS_Level(0), pos, sks); + update_cache(cached, trees); + + return LMS_Tree_Node(trees.front().tree->treetop().root()); +} + +LMS_PublicKey HSS_LMS_PrivateKeyInternal::top_lms_public_key() const { + const auto& top_params = hss_params().params_at_level(HSS_Level(0)); + return LMS_PublicKey(top_params.lms_params(), top_params.lmots_params(), m_identifier, root()); +} + +bool HSS_LMS_PrivateKeyInternal::root_matches_seed() const { + const LMS_PublicKey computed(hss_derive_root_lms_private_key()); + return computed.to_bytes() == top_lms_public_key().to_bytes(); } std::vector HSS_LMS_PrivateKeyInternal::sign(std::span msg) const { - std::vector sig(HSS_Signature::size(hss_params())); + const auto& params = hss_params(); + const HSS_Level bottom(params.L() - 1); + const auto& bottom_params = params.params_at_level(bottom); + + std::vector sig(HSS_Signature::size(params)); BufferStuffer sig_stuffer(sig); - sig_stuffer.append(store_be(hss_params().L() - 1)); - - std::vector q = derive_lms_leaf_indices_from_hss_index(reserve_next_idx(), hss_params()); - - // Derive LMS private keys and compute buffers - std::vector lms_key_at_layer; - std::vector> out_lms_sig_buffer_at_layer; - std::vector> out_child_pk_buffer_at_layer; - for(HSS_Level layer(0); layer < hss_params().L(); ++layer) { - // Generate key for current layer - const HSS_LMS_Params::LMS_LMOTS_Params_Pair& layer_params = hss_params().params_at_level(layer); - if(layer == HSS_Level(0)) { - lms_key_at_layer.push_back(hss_derive_root_lms_private_key()); - } else { - lms_key_at_layer.push_back( - hss_derive_child_lms_private_key(layer_params, lms_key_at_layer.back(), q.at(layer.get() - 1))); - out_child_pk_buffer_at_layer.push_back(sig_stuffer.next(LMS_PublicKey::size(layer_params.lms_params()))); + sig_stuffer.append(store_be(bottom)); // Nspk + + HSS_Sig_Idx idx(0); + Tree_Cache cached; + + { + const lock_guard_type lock(m_cache_mutex); + + // Reserving the index while holding the lock means the cache of this + // object only ever moves forward, even when signing concurrently + idx = reserve_next_idx(); + cached = m_cache; + } + + const auto pos = tree_position(idx); + const auto sks = derive_lms_private_keys(pos); + + auto trees = cached; + if(!populate_cache(trees, pos, sks)) { + // Some loaded data did not match the seed; start over from the seed alone + trees = Tree_Cache(params.L().get()); + if(!populate_cache(trees, pos, sks)) { + throw Internal_Error("HSS-LMS tree computed from the seed is inconsistent"); } - out_lms_sig_buffer_at_layer.push_back(sig_stuffer.next( - LMS_Signature::size(layer_params.lms_params(), layer_params.lmots_params()))); } + + update_cache(cached, trees); + + // sig[i-1] || pub[i] for each level below the top + for(HSS_Level level(1); level <= bottom; ++level) { + sig_stuffer.append(trees.at(level.get()).tree->signed_pub_key()); + } + + const auto bottom_sig = sig_stuffer.next( + LMS_Signature::size(bottom_params.lms_params(), bottom_params.lmots_params())); BOTAN_ASSERT_NOMSG(sig_stuffer.full()); - // Sign and write the signature from bottom layer to root layer - std::vector current_pk; - for(int32_t layer_it = hss_params().L().get() - 1; layer_it >= 0; --layer_it) { - HSS_Level layer(layer_it); - if(layer == hss_params().L() - 1) { - current_pk = - lms_key_at_layer.at(layer.get()) - .sign_and_get_pk(out_lms_sig_buffer_at_layer.at(layer.get()), q.at(layer.get()), LMS_Message(msg)) - .to_bytes(); - } else { - copy_mem(out_child_pk_buffer_at_layer.at(layer.get()), current_pk); - current_pk = - lms_key_at_layer.at(layer.get()) - .sign_and_get_pk(out_lms_sig_buffer_at_layer.at(layer.get()), q.at(layer.get()), LMS_Message(current_pk)) - .to_bytes(); + const auto& bottom_subtree = trees.at(bottom.get()).subtree; + sks.at(bottom.get()) + .sign_with_nodes(bottom_sig, + pos.q.at(bottom.get()), + LMS_Message(msg), + trees.at(bottom.get()).tree->treetop(), + (bottom_subtree != nullptr) ? &bottom_subtree->subtree() : nullptr); + + CT::unpoison(sig); + + const HSS_LMS_PublicKeyInternal public_key(params.L(), top_lms_public_key()); + + const bool valid = [&] { + try { + return public_key.verify_signature(msg, HSS_Signature::from_bytes_or_throw(sig)); + } catch(const Decoding_Error&) { + return false; } + }(); + + if(!valid) { + // Discard the cache so the next signature is computed from the seed alone + const lock_guard_type lock(m_cache_mutex); + m_cache = Tree_Cache(params.L().get()); + throw Internal_Error("HSS-LMS signature failed verification"); } return sig; @@ -345,12 +694,7 @@ LMS_PrivateKey HSS_LMS_PrivateKeyInternal::hss_derive_child_lms_private_key( } HSS_LMS_PublicKeyInternal HSS_LMS_PublicKeyInternal::create(const HSS_LMS_PrivateKeyInternal& hss_sk) { - const auto& hss_params = hss_sk.hss_params(); - - const auto root_sk = hss_sk.hss_derive_root_lms_private_key(); - LMS_PublicKey top_pub_key = LMS_PublicKey(root_sk); - - return HSS_LMS_PublicKeyInternal(hss_params.L(), std::move(top_pub_key)); + return HSS_LMS_PublicKeyInternal(hss_sk.hss_params().L(), hss_sk.top_lms_public_key()); } std::shared_ptr HSS_LMS_PublicKeyInternal::from_bytes_or_throw( diff --git a/src/lib/pubkey/hss_lms/hss.h b/src/lib/pubkey/hss_lms/hss.h index ccded4e862c..df543eeb2cf 100644 --- a/src/lib/pubkey/hss_lms/hss.h +++ b/src/lib/pubkey/hss_lms/hss.h @@ -10,11 +10,13 @@ #define BOTAN_HSS_H_ #include +#include #include #include #include #include #include +#include #include #include #include @@ -118,11 +120,74 @@ class BOTAN_TEST_API HSS_LMS_Params final { HSS_Sig_Idx m_max_sig_count; }; +/** + * @brief The encodings of an HSS-LMS private key + */ +enum class HSS_LMS_PrivateKey_Format : uint8_t { + /** The parameters, index and secret only (OID HSS-LMS-Private-Key-legacy) */ + // TODO(Botan4) Remove the legacy format + Legacy, + /** Additionally the root and cached tree data (OID HSS-LMS-Private-Key) */ + Current, + /** Raw bytes, which carry no OID: either of the above */ + // TODO(Botan4) Remove; raw bytes are then always in the current format + Either, +}; + +/** + * @brief Public data of one LMS tree of the HSS hypertree, kept between signatures. + */ +class HSS_Cached_Tree final { + public: + HSS_Cached_Tree(uint64_t tree_number, Merkle_Treetop treetop, std::vector signed_pub_key) : + m_tree_number(tree_number), m_treetop(std::move(treetop)), m_signed_pub_key(std::move(signed_pub_key)) {} + + /** + * @brief The position of the tree within its level, counting from the left. + */ + uint64_t tree_number() const { return m_tree_number; } + + const Merkle_Treetop& treetop() const { return m_treetop; } + + /** + * @brief The parent tree's LMS signature over this tree's public key, + * followed by that public key (sig[i-1] || pub[i] of an HSS + * signature). Empty for the top tree. + */ + std::span signed_pub_key() const { return m_signed_pub_key; } + + private: + uint64_t m_tree_number; + Merkle_Treetop m_treetop; + std::vector m_signed_pub_key; +}; + +/** + * @brief A subtree of an HSS_Cached_Tree, kept between signatures. + */ +class HSS_Cached_Subtree final { + public: + HSS_Cached_Subtree(uint64_t tree_number, Merkle_Subtree subtree) : + m_tree_number(tree_number), m_subtree(std::move(subtree)) {} + + uint64_t tree_number() const { return m_tree_number; } + + const Merkle_Subtree& subtree() const { return m_subtree; } + + private: + uint64_t m_tree_number; + Merkle_Subtree m_subtree; +}; + /** * @brief The internal HSS-LMS private key. * * Note that the format is not specified in the RFC 8554, * and is Botan specific. + * + * Besides the secret, the key keeps the public nodes and signatures of the + * LMS trees in use, so that a signature only requires a single LM-OTS + * signature in the common case. This data is also stored in the encoding. */ class HSS_LMS_PrivateKeyInternal final { public: @@ -138,10 +203,12 @@ class HSS_LMS_PrivateKeyInternal final { * @brief Parse a private HSS-LMS key. * * @param key_bytes The private key bytes to parse. + * @param format The expected format of @p key_bytes. * @return The internal HSS-LMS private key. * @throws Decoding_Error If parsing the private key fails. */ - static std::shared_ptr from_bytes_or_throw(std::span key_bytes); + static std::shared_ptr from_bytes_or_throw(std::span key_bytes, + HSS_LMS_PrivateKey_Format format); /** * @brief Returns the used HSS-LMS parameters. @@ -153,6 +220,20 @@ class HSS_LMS_PrivateKeyInternal final { */ secure_vector to_bytes() const; + /** + * @brief The public key of the top LMS tree. + * + * If the key was loaded from an encoding that does not contain the + * root of the top tree, this computes the whole top tree. + */ + LMS_PublicKey top_lms_public_key() const; + + /** + * @brief Check that the root of the top tree matches the seed, which + * requires computing the whole top tree. + */ + bool root_matches_seed() const; + /** * @brief Get the number of remaining signatures for this key. */ @@ -177,10 +258,9 @@ class HSS_LMS_PrivateKeyInternal final { * * See RFC 8554 6.2 - Algorithm 8. * - * For each signature creation the hypertree is computed once - * again, so no data is stored between multiple signatures. However, - * storing data between multiple signatures could be an optimization - * if applications create multiple signatures in one go. + * Trees are only computed when they are first used, or when the + * cached data does not match the seed. The signature is verified + * before it is returned. * * @param msg The message to sign. */ @@ -206,6 +286,36 @@ class HSS_LMS_PrivateKeyInternal final { void _const_time_unpoison() const { CT::unpoison(m_hss_seed); } private: + /** + * @brief The tree and leaf used at each level for some HSS index. + */ + struct Tree_Position final { + std::vector q; + std::vector tree_number; + }; + + /** + * @brief A cached tree as found in the encoding, before validation. + */ + struct Encoded_Tree final { + HSS_Level level; + uint64_t tree_number; + std::span row; + std::span signed_pub_key; + }; + + /** + * @brief The most recently used tree of some level, and the subtree of + * it containing the most recently used leaf. + */ + struct Cached_Level final { + std::shared_ptr tree; + std::shared_ptr subtree; + }; + + // One entry per level, starting at the top + using Tree_Cache = std::vector; + HSS_LMS_PrivateKeyInternal(HSS_LMS_Params hss_params, LMS_Seed hss_seed, LMS_Identifier identifier); /** @@ -214,10 +324,49 @@ class HSS_LMS_PrivateKeyInternal final { */ HSS_Sig_Idx reserve_next_idx() const; + Tree_Position tree_position(HSS_Sig_Idx idx) const; + /** - * @brief Returns the size in bytes the key would have in its encoded format. + * @brief Derive the LMS private keys of the trees used at @p pos, from top to bottom. */ - size_t size() const; + std::vector derive_lms_private_keys(const Tree_Position& pos) const; + + /** + * @brief Keep the encoded trees which are consistent with each other, + * the root, and the index @p idx. + */ + void adopt_encoded_trees(HSS_Sig_Idx idx, const std::vector& encoded); + + // The following compute whatever @p cache is missing to sign at @p pos. + // This may wait on threads which are themselves signing with this key, + // so m_cache_mutex must not be held. The functions returning bool return + // false if cached data turned out not to match the seed. + + bool populate_cache(Tree_Cache& cache, const Tree_Position& pos, const std::vector& sks) const; + + bool ensure_tree(Tree_Cache& cache, + HSS_Level level, + const Tree_Position& pos, + const std::vector& sks) const; + + bool ensure_subtree(Tree_Cache& cache, HSS_Level level, const Tree_Position& pos, const LMS_PrivateKey& sk) const; + + /** + * @brief Replace the cache by @p updated, unless it was updated or + * discarded since @p cached was read from it. + */ + void update_cache(const Tree_Cache& cached, const Tree_Cache& updated) const; + + /** + * @brief Record the root of the top tree as computed from the seed. + * @throws Invalid_State if it does not match the root already known. + */ + void set_root(const LMS_Tree_Node& root) const; + + /** + * @brief The root of the top tree, computing that tree if the root is not known. + */ + LMS_Tree_Node root() const; /** * @brief Derive the seed and identifier of an LMS tree from its parent LMS tree. @@ -239,6 +388,12 @@ class HSS_LMS_PrivateKeyInternal final { LMS_Identifier m_identifier; Stateful_Key_Index_Registry::KeyId m_keyid; const size_t m_sig_size; + + mutable mutex_type m_cache_mutex; + // Root of the top tree, if known + mutable std::optional m_root; + // The trees are immutable, and only replaced while holding the mutex + mutable Tree_Cache m_cache; }; class HSS_Signature; diff --git a/src/lib/pubkey/hss_lms/hss_lms.cpp b/src/lib/pubkey/hss_lms/hss_lms.cpp index b133c0190e1..8a5f3b4afbb 100644 --- a/src/lib/pubkey/hss_lms/hss_lms.cpp +++ b/src/lib/pubkey/hss_lms/hss_lms.cpp @@ -134,6 +134,24 @@ std::unique_ptr HSS_LMS_PublicKey::generate_another(RandomNumberGen HSS_LMS_PrivateKey::HSS_LMS_PrivateKey(std::span private_key) : HSS_LMS_PrivateKey(AlgorithmIdentifier(), private_key) {} +namespace { + +HSS_LMS_PrivateKey_Format private_key_format(const OID& oid) { + // TODO(Botan4) Remove the legacy format, and accept only the current one + if(oid.empty()) { + // Raw bytes, such as from raw_private_key_bits() of this or an older version + return HSS_LMS_PrivateKey_Format::Either; + } else if(oid == OID::from_string("HSS-LMS-Private-Key-legacy")) { + return HSS_LMS_PrivateKey_Format::Legacy; + } else if(oid == OID::from_string("HSS-LMS-Private-Key")) { + return HSS_LMS_PrivateKey_Format::Current; + } else { + throw Decoding_Error("Unexpected OID for HSS-LMS private key"); + } +} + +} // namespace + HSS_LMS_PrivateKey::HSS_LMS_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { // The HSS/LMS parameters are carried in the key bits; no AlgorithmIdentifier // parameters are defined. @@ -141,7 +159,7 @@ HSS_LMS_PrivateKey::HSS_LMS_PrivateKey(const AlgorithmIdentifier& alg_id, std::s throw Decoding_Error("Unexpected parameters for HSS-LMS private key"); } - m_private = HSS_LMS_PrivateKeyInternal::from_bytes_or_throw(key_bits); + m_private = HSS_LMS_PrivateKeyInternal::from_bytes_or_throw(key_bits, private_key_format(alg_id.oid())); const auto scope = CT::scoped_poison(*m_private); m_public = std::make_shared(HSS_LMS_PublicKeyInternal::create(*m_private)); CT::unpoison(*m_public); @@ -178,11 +196,15 @@ std::unique_ptr HSS_LMS_PrivateKey::public_key() const { // We use a separate algorithm identifier for the private key since we use a Botan scoped OID for it. // This is necessary since the private key format is implementation specific, since it is not defined -// in RFC 8554. +// in RFC 8554. Each revision of the format gets its own OID. AlgorithmIdentifier HSS_LMS_PrivateKey::pkcs8_algorithm_identifier() const { return AlgorithmIdentifier(OID::from_string("HSS-LMS-Private-Key"), AlgorithmIdentifier::USE_EMPTY_PARAM); } +bool HSS_LMS_PrivateKey::check_key(RandomNumberGenerator& /*rng*/, bool strong) const { + return !strong || m_private->root_matches_seed(); +} + std::optional HSS_LMS_PrivateKey::remaining_operations() const { return m_private->remaining_operations().get(); } diff --git a/src/lib/pubkey/hss_lms/hss_lms.h b/src/lib/pubkey/hss_lms/hss_lms.h index db74b350ac3..c22988f8219 100644 --- a/src/lib/pubkey/hss_lms/hss_lms.h +++ b/src/lib/pubkey/hss_lms/hss_lms.h @@ -92,20 +92,40 @@ BOTAN_DIAGNOSTIC_IGNORE_INHERITED_VIA_DOMINANCE * the number and size of LMS layers of the chosen HSS/LMS instance. For the selection * of a sensible parameter set, refer to RFC 8554 6.4. * - * The format of the HSS/LMS private key is not defined in - * RFC 8554. We use the following format (big endian): + * The format of the HSS/LMS private key is not defined in RFC 8554. We use the + * following format (big endian), identified by the OID HSS-LMS-Private-Key + * (1.3.6.1.4.1.25258.1.19): * * PrivateKey = u32str(L) || u64str(idx) || * u32str(LMS algorithm id (root layer)) || u32str(LMOTS algorithm id (root layer)) || * ... || * u32str(LMS algorithm id (bottom layer)) || u32str(LMOTS algorithm id (bottom layer)) || - * HSS_SEED || HSS_Identifier + * HSS_SEED || HSS_Identifier || T[1] || + * u32str(N) || Section[0] || ... || Section[N-1] * * L: Number of LMS layers * Idx: Number of signatures already created using this private key * HSS_SEED: Seed to derive LMS Seeds (see RFC 8554 Appendix A) like in SECRET_METHOD 2 of * https://github.com/cisco/hash-sigs. As long as the hash functions output length. * HSS_Identifier: 16 bytes long. + * T[1]: Root of the top LMS tree. + * + * Section = u32str(tag) || u32str(length) || body + * + * Sections with unknown tags are ignored. Tag 1 holds the public data of an + * LMS tree used by the next signature, so that it need not be recomputed: + * + * body = u32str(level) || u64str(tree number) || nodes || [ sig[level-1] || pub[level] ] + * + * nodes: The nodes at height max(0, h - 10) of the tree, from left to right. + * sig[level-1] || pub[level]: Only for levels below the top; the signature + * by the parent tree over the tree's public key, followed by that + * public key, as they appear in an HSS signature. + * + * Keys in the legacy format, identified by the OID HSS-LMS-Private-Key-legacy + * (1.3.6.1.4.1.25258.1.13), which only consists of the fields from L to + * HSS_Identifier, are also accepted. Raw key bytes, which carry no OID, are + * taken to be in the legacy format if nothing follows HSS_Identifier. * * The HSS/LMS instance to use for creating new keys is defined using an algorithm parameter sting, * i.e. to define which hash function (hash), LMS tree height (h) @@ -157,6 +177,12 @@ class BOTAN_PUBLIC_API(3, 5) HSS_LMS_PrivateKey final : public virtual HSS_LMS_P AlgorithmIdentifier pkcs8_algorithm_identifier() const override; + /** + * A strong check computes the whole top LMS tree, to verify that the + * public key matches the secret seed. + */ + bool check_key(RandomNumberGenerator& rng, bool strong) const override; + bool stateful_operation() const override { return true; } /** diff --git a/src/lib/pubkey/hss_lms/lms.cpp b/src/lib/pubkey/hss_lms/lms.cpp index 01e41417376..2466af4271d 100644 --- a/src/lib/pubkey/hss_lms/lms.cpp +++ b/src/lib/pubkey/hss_lms/lms.cpp @@ -16,6 +16,7 @@ #include #include #include +#include namespace Botan { namespace { @@ -85,16 +86,17 @@ void lms_gen_leaf(StrongSpan out, hash.final(out); } -auto lms_gen_leaves_func(const LMS_PrivateKey& lms_sk) { +Merkle_Leaf_Fn lms_gen_leaves_func(const LMS_PrivateKey& lms_sk) { // The hash engine is created once here and reused for all leaves - return [engine = Hash_Engine::create_or_throw(lms_sk.lmots_params().hash_name()), lms_sk]( - std::span out, LMS_Tree_Node_Idx first_idx, size_t count) { + return [engine = std::shared_ptr(Hash_Engine::create_or_throw(lms_sk.lmots_params().hash_name())), + lms_sk](std::span out, uint32_t first_idx, uint32_t count) { const size_t m = lms_sk.lms_params().m(); const auto& identifier = lms_sk.identifier(); // The OTS public key hashes of all requested leaves std::vector ks(count * m); - lmots_compute_pubkeys(ks, lms_sk.lmots_params(), identifier, first_idx, count, lms_sk.seed(), *engine); + lmots_compute_pubkeys( + ks, lms_sk.lmots_params(), identifier, LMS_Tree_Node_Idx(first_idx), count, lms_sk.seed(), *engine); // Leaf node hash: H(I || u32str(r) || u16str(D_LEAF) || K) const size_t prefix_len = identifier.size() + sizeof(uint32_t) + sizeof(uint16_t); @@ -103,7 +105,7 @@ auto lms_gen_leaves_func(const LMS_PrivateKey& lms_sk) { std::vector> prefix_spans(count); std::vector> k_spans(count); for(size_t i = 0; i != count; ++i) { - const uint32_t r = (uint32_t(1) << lms_sk.lms_params().h()) + first_idx.get() + static_cast(i); + const uint32_t r = (uint32_t(1) << lms_sk.lms_params().h()) + first_idx + static_cast(i); const auto prefix_span = std::span(prefixes).subspan(i * prefix_len, prefix_len); BufferStuffer prefix(prefix_span); prefix.append(identifier); @@ -117,27 +119,53 @@ auto lms_gen_leaves_func(const LMS_PrivateKey& lms_sk) { }; } -void lms_treehash(StrongSpan out_root, - std::optional> out_auth_path, - std::optional leaf_idx, - const LMS_PrivateKey& lms_sk) { - auto hash_pair_func = get_hash_pair_func_for_identifier(lms_sk.lms_params(), lms_sk.identifier()); - auto gen_leaves = lms_gen_leaves_func(lms_sk); - TreeAddress lms_tree_address(lms_sk.lms_params().h()); - - treehash(out_root, - out_auth_path, - leaf_idx, - lms_sk.lms_params().m(), - LMS_TreeLayerIndex(lms_sk.lms_params().h()), - 0, - std::move(hash_pair_func), - std::move(gen_leaves), - lms_tree_address); +/** + * Interior node hash: H(I || u32str(r) || u16str(D_INTR) || left || right) + * + * The node at height j with index t has node number r = 2^(h-j) + t + */ +Merkle_Node_Fn lms_node_func(const LMS_Params& lms_params, const LMS_Identifier& identifier) { + return + [engine = std::shared_ptr(Hash_Engine::create_or_throw(lms_params.hash_name(), identifier.get())), + h = lms_params.h(), + m = lms_params.m()]( + std::span out, uint32_t j, uint32_t first_t, uint32_t count, std::span children) { + constexpr size_t prefix_len = sizeof(uint32_t) + sizeof(uint16_t); + std::vector prefixes(count * prefix_len); + std::vector> outs(count); + std::vector> prefix_spans(count); + std::vector> child_spans(count); + for(size_t i = 0; i != count; ++i) { + const uint32_t r = (uint32_t(1) << (h - j)) + first_t + static_cast(i); + const auto prefix_span = std::span(prefixes).subspan(i * prefix_len, prefix_len); + BufferStuffer prefix(prefix_span); + prefix.append(store_be(r)); + prefix.append(store_be(D_INTR)); + prefix_spans[i] = prefix_span; + outs[i] = out.subspan(i * m, m); + child_spans[i] = children.subspan(2 * i * m, 2 * m); + } + engine->batch_hash(outs, prefix_spans, child_spans); + }; +} + +Merkle_Tree_Builder lms_merkle_tree(const LMS_PrivateKey& sk) { + constexpr uint32_t leaf_batch = 32; + return Merkle_Tree_Builder(sk.lms_params().h(), + sk.lms_params().m(), + leaf_batch, + lms_gen_leaves_func(sk), + lms_node_func(sk.lms_params(), sk.identifier())); } } // namespace +Merkle_Treetop lms_treetop_from_row(const LMS_Params& lms_params, + const LMS_Identifier& identifier, + std::span row) { + return Merkle_Treetop::from_row(lms_params.h(), lms_params.m(), row, lms_node_func(lms_params, identifier)); +} + std::unique_ptr LMS_Params::hash() const { return HashFunction::create_or_throw(hash_name()); } @@ -274,24 +302,40 @@ LMS_Params::LMS_Params(LMS_Algorithm_Type algorithm_type, std::string_view hash_ LMS_PublicKey LMS_PrivateKey::sign_and_get_pk(StrongSpan out_sig, LMS_Tree_Node_Idx q, const LMS_Message& msg) const { - // Pre-alloc space for the signature + const auto [treetop, subtree] = build_tree(q); + sign_with_nodes(out_sig, q, msg, treetop, &subtree); + const auto root = treetop.root(); + return LMS_PublicKey(lms_params(), lmots_params(), identifier(), LMS_Tree_Node(root.begin(), root.end())); +} + +std::pair LMS_PrivateKey::build_tree(LMS_Tree_Node_Idx q) const { + BOTAN_ARG_CHECK(q.get() < (uint32_t(1) << lms_params().h()), "Invalid LMS leaf index"); + return lms_merkle_tree(*this).build(q.get()); +} + +std::optional LMS_PrivateKey::build_subtree(const Merkle_Treetop& treetop, LMS_Tree_Node_Idx q) const { + BOTAN_ARG_CHECK(q.get() < (uint32_t(1) << lms_params().h()), "Invalid LMS leaf index"); + return lms_merkle_tree(*this).build_subtree(treetop, q.get()); +} + +void LMS_PrivateKey::sign_with_nodes(StrongSpan out_sig, + LMS_Tree_Node_Idx q, + const LMS_Message& msg, + const Merkle_Treetop& treetop, + const Merkle_Subtree* subtree) const { + const uint32_t h = lms_params().h(); BOTAN_ARG_CHECK(out_sig.size() == LMS_Signature::size(lms_params(), lmots_params()), "Invalid output buffer size"); + BOTAN_ARG_CHECK(q.get() < (uint32_t(1) << h), "Invalid LMS leaf index"); + BOTAN_ARG_CHECK(treetop.h() == h && treetop.n() == lms_params().m(), "Treetop does not belong to this tree"); BufferStuffer sig_stuffer(out_sig); sig_stuffer.append(store_be(q)); const LMOTS_Private_Key lmots_sk(lmots_params(), identifier(), q, seed()); lmots_sk.sign(sig_stuffer.next(LMOTS_Signature::size(lmots_params())), msg); sig_stuffer.append(store_be(lms_params().algorithm_type())); - const auto auth_path_buffer = sig_stuffer.next(lms_params().m() * lms_params().h()); + treetop.auth_path(sig_stuffer.next(h * lms_params().m()), q.get(), subtree); BOTAN_ASSERT_NOMSG(sig_stuffer.full()); - - const TreeAddress lms_tree_address(lms_params().h()); - LMS_Tree_Node pk_buffer(lms_params().m()); - lms_treehash(StrongSpan(pk_buffer.get()), auth_path_buffer, q, *this); - - CT::unpoison(pk_buffer); - return LMS_PublicKey(lms_params(), lmots_params(), identifier(), std::move(pk_buffer)); } LMS_PublicKey LMS_PublicKey::from_bytes_or_throw(BufferSlicer& slicer) { @@ -380,7 +424,7 @@ LMS_Signature LMS_Signature::from_bytes_or_throw(BufferSlicer& slicer) { LMS_PublicKey::LMS_PublicKey(const LMS_PrivateKey& sk) : /* NOLINT(*-slicing) */ LMS_Instance(sk), m_lms_root(sk.lms_params().m()) { - lms_treehash(StrongSpan(m_lms_root), std::nullopt, std::nullopt, sk); + copy_mem(m_lms_root, lms_merkle_tree(sk).root()); } bool LMS_PublicKey::verify_signature(const LMS_Message& msg, const LMS_Signature& sig) const { diff --git a/src/lib/pubkey/hss_lms/lms.h b/src/lib/pubkey/hss_lms/lms.h index dc36e3ad07b..73805a1196f 100644 --- a/src/lib/pubkey/hss_lms/lms.h +++ b/src/lib/pubkey/hss_lms/lms.h @@ -11,8 +11,10 @@ #include #include +#include #include +#include #include #include #include @@ -181,6 +183,17 @@ class BOTAN_TEST_API LMS_Instance { LMS_Identifier m_identifier; }; +/** + * @brief Compute the treetop of an LMS tree from its lowest row (see Merkle_Treetop::row()). + * + * @param lms_params The LMS parameters of the tree. + * @param identifier The identifier (I) of the tree. + * @param row The nodes at height Merkle_Treetop::subtree_height(h) from left to right. + */ +BOTAN_TEST_API Merkle_Treetop lms_treetop_from_row(const LMS_Params& lms_params, + const LMS_Identifier& identifier, + std::span row); + class LMS_PublicKey; /** @@ -212,6 +225,37 @@ class BOTAN_TEST_API LMS_PrivateKey final : public LMS_Instance { LMS_Tree_Node_Idx q, const LMS_Message& msg) const; + /** + * @brief Compute the whole tree. + * + * @return The treetop, and the subtree containing leaf @p q. + */ + std::pair build_tree(LMS_Tree_Node_Idx q) const; + + /** + * @brief Compute the subtree containing leaf @p q. + * + * @return The subtree, or nullopt if its root does not match @p treetop + */ + std::optional build_subtree(const Merkle_Treetop& treetop, LMS_Tree_Node_Idx q) const; + + /** + * @brief Sign a message using leaf @p q, taking the authentication path + * from already computed nodes (RFC 8554 5.4.1). + * + * @param out_sig Output buffer of size LMS_Signature::size() + * @param q The leaf to sign with + * @param msg The message to sign + * @param treetop The treetop of this tree + * @param subtree The subtree containing @p q. Unused, and may be null, + * if the subtree height is zero. + */ + void sign_with_nodes(StrongSpan out_sig, + LMS_Tree_Node_Idx q, + const LMS_Message& msg, + const Merkle_Treetop& treetop, + const Merkle_Subtree* subtree) const; + private: LMS_Seed m_seed; }; diff --git a/src/lib/pubkey/pk_algs.cpp b/src/lib/pubkey/pk_algs.cpp index a2b7058a5aa..04e5836c465 100644 --- a/src/lib/pubkey/pk_algs.cpp +++ b/src/lib/pubkey/pk_algs.cpp @@ -418,7 +418,8 @@ std::unique_ptr load_private_key(const AlgorithmIdentifier& alg_id, #endif #if defined(BOTAN_HAS_XMSS_RFC8391) - if(alg_name == "XMSS") { + // TODO(Botan4) Remove the legacy private key format with OID XMSS + if(alg_name == "XMSS-Private-Key" || alg_name == "XMSS") { return std::make_unique(alg_id, key_bits); } #endif @@ -436,7 +437,8 @@ std::unique_ptr load_private_key(const AlgorithmIdentifier& alg_id, #endif #if defined(BOTAN_HAS_HSS_LMS) - if(alg_name == "HSS-LMS-Private-Key") { + // TODO(Botan4) Remove the legacy format HSS-LMS-Private-Key-legacy + if(alg_name == "HSS-LMS-Private-Key" || alg_name == "HSS-LMS-Private-Key-legacy") { return std::make_unique(alg_id, key_bits); } #endif diff --git a/src/lib/pubkey/xmss/info.txt b/src/lib/pubkey/xmss/info.txt index d0c5943930a..3ad1015489a 100644 --- a/src/lib/pubkey/xmss/info.txt +++ b/src/lib/pubkey/xmss/info.txt @@ -29,5 +29,6 @@ rng hash hash_engine stateful_key_index +tree_hash trunc_hash diff --git a/src/lib/pubkey/xmss/xmss.h b/src/lib/pubkey/xmss/xmss.h index 8c8fca52d5d..f074d818a68 100644 --- a/src/lib/pubkey/xmss/xmss.h +++ b/src/lib/pubkey/xmss/xmss.h @@ -164,8 +164,26 @@ enum class WOTS_Derivation_Method : uint8_t { /** * An XMSS: Extended Hash-Based Signature private key. - * The XMSS private key does not support the X509 and PKCS7 standard. Instead - * the raw format described in [1] is used. + * + * The format of an XMSS private key is not standardized. We use the following + * format (big endian), identified by the OID XMSS-Private-Key + * (1.3.6.1.4.1.25258.1.20): + * + * PrivateKey = u32str(OID) || root || SEED || u32str(idx) || SK_PRF || S_XMSS || + * u8(WOTS+ derivation method) || + * u32str(N) || Section[0] || ... || Section[N-1] + * + * Section = u32str(tag) || u32str(length) || body + * + * Sections with unknown tags are ignored. Tag 1 holds the nodes at height + * max(0, h - 10) of the tree from left to right, so that they need not be + * recomputed. + * + * Keys in the legacy format, which ends with the WOTS+ derivation method (or + * before it, for keys created by Botan 2), identified by the OID XMSS and + * wrapped in an OCTET STRING, are also accepted. Raw key bytes, which carry no + * OID, are taken to be in the legacy format if they are wrapped in an OCTET + * STRING or nothing follows the WOTS+ derivation method. * * [1] XMSS: Extended Hash-Based Signatures, * Request for Comments: 8391 @@ -261,14 +279,11 @@ class BOTAN_PUBLIC_API(2, 0) XMSS_PrivateKey final : public virtual XMSS_PublicK secure_vector private_key_bits() const override; + AlgorithmIdentifier pkcs8_algorithm_identifier() const override; + /** * Generates a non standardized byte sequence representing the XMSS - * private key. - * - * @return byte sequence consisting of the following elements in order: - * 4-byte OID, n-byte root node, n-byte public seed, - * 4-byte unused leaf index, n-byte prf seed, n-byte private seed. - * At last 1-byte that encodes the WOTS+ key derivation method. + * private key, in the format described above. **/ secure_vector raw_private_key() const; @@ -277,43 +292,27 @@ class BOTAN_PUBLIC_API(2, 0) XMSS_PrivateKey final : public virtual XMSS_PublicK private: friend class XMSS_Signature_Operation; - // The seeds and the precomputed Merkle root produced during key - // generation, used to construct the (immutable) public key before the - // derived private key body runs. - struct Keygen_Material; - - XMSS_PrivateKey(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, - WOTS_Derivation_Method wots_derivation_method, - Keygen_Material material); + explicit XMSS_PrivateKey(std::shared_ptr sk); - static Keygen_Material generate_keygen_material(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, - RandomNumberGenerator& rng, - WOTS_Derivation_Method wots_derivation_method); + /** + * Reserve the next unused leaf + * + * @param auth_path Output buffer for the leaf's authentication path + * @param hash The hash function to use + * @return The index of the leaf + */ + size_t reserve_leaf(std::span auth_path, XMSS_Hash& hash) const; - size_t reserve_unused_leaf_index(); + /** + * Discard the tree nodes kept for signing, so that they are recomputed + * from the seed + */ + void discard_cached_tree() const; const secure_vector& prf_value() const; XMSS_WOTS_PrivateKey wots_private_key_for(const XMSS_Address& adrs, XMSS_Hash& hash) const; - /** - * Algorithm 9: "treeHash" - * Computes the internal n-byte nodes of a Merkle tree. - * - * @param start_idx The start index. - * @param target_node_height Height of the target node. - * @param adrs Address of the tree containing the target node. - * @param hash The hash function to use - * - * @return The root node of a tree of height target_node height with the - * leftmost leaf being the hash of the WOTS+ pk with index - * start_idx. - **/ - secure_vector tree_hash(size_t start_idx, - size_t target_node_height, - const XMSS_Address& adrs, - XMSS_Hash& hash) const; - std::shared_ptr m_private; }; diff --git a/src/lib/pubkey/xmss/xmss_common_ops.cpp b/src/lib/pubkey/xmss/xmss_common_ops.cpp index 0cf588d36bd..dbc3883dafc 100644 --- a/src/lib/pubkey/xmss/xmss_common_ops.cpp +++ b/src/lib/pubkey/xmss/xmss_common_ops.cpp @@ -46,6 +46,61 @@ void XMSS_Common_Ops::randomize_tree_hash(secure_vector& result, hash.h(result, key, concat_xor); } +void XMSS_Common_Ops::randomize_tree_hashes(std::span out, + std::span children, + std::span addrs, + std::span seed, + XMSS_Hash& hash, + size_t element_size) { + const size_t count = addrs.size(); + const size_t n = element_size; + + BOTAN_ASSERT_NOMSG(out.size() == count * n); + BOTAN_ASSERT_NOMSG(children.size() == count * 2 * n); + + if(count == 0) { + return; + } + + const size_t adrs_len = addrs[0].size(); + + // Per pair the three PRF addresses (key, bitmask left/right), the key, + // and the masked concatenation of both children + std::vector adrs_buf(3 * count * adrs_len); + secure_vector keys(count * n); + secure_vector masked(count * 2 * n); + + std::vector> prf_outs(3 * count); + std::vector> prf_ins(3 * count); + + for(size_t p = 0; p != count; ++p) { + const auto adrs_lane = [&](size_t lane, XMSS_Address::Key_Mask mode, std::span dest) { + addrs[p].set_key_mask_mode(mode); + const auto lane_adrs = std::span(adrs_buf).subspan(lane * adrs_len, adrs_len); + copy_mem(lane_adrs, addrs[p].bytes()); + prf_ins[lane] = lane_adrs; + prf_outs[lane] = dest; + }; + adrs_lane(3 * p, XMSS_Address::Key_Mask::Key_Mode, std::span(keys).subspan(p * n, n)); + adrs_lane(3 * p + 1, XMSS_Address::Key_Mask::Mask_MSB_Mode, std::span(masked).subspan(2 * p * n, n)); + adrs_lane(3 * p + 2, XMSS_Address::Key_Mask::Mask_LSB_Mode, std::span(masked).subspan((2 * p + 1) * n, n)); + } + hash.prf_batch(prf_outs, seed, prf_ins); + + // The bitmasks of all pairs are laid out like the children + xor_buf(std::span(masked), children); + + std::vector> h_outs(count); + std::vector> h_keys(count); + std::vector> h_ins(count); + for(size_t p = 0; p != count; ++p) { + h_outs[p] = out.subspan(p * n, n); + h_keys[p] = std::span(keys).subspan(p * n, n); + h_ins[p] = std::span(masked).subspan(2 * p * n, 2 * n); + } + hash.h_batch(h_outs, h_keys, h_ins); +} + void XMSS_Common_Ops::create_l_tree(secure_vector& result, const wots_keysig_t& pk, XMSS_Address adrs, diff --git a/src/lib/pubkey/xmss/xmss_common_ops.h b/src/lib/pubkey/xmss/xmss_common_ops.h index f9240d6cd50..efcd5cd9560 100644 --- a/src/lib/pubkey/xmss/xmss_common_ops.h +++ b/src/lib/pubkey/xmss/xmss_common_ops.h @@ -63,6 +63,27 @@ class XMSS_Common_Ops { XMSS_Hash& hash, size_t element_size); + /** + * Algorithm 7: "RAND_HASH", applied to many pairs of nodes at once, + * batching the hash calls across all of them. + * + * @param[out] out The resulting randomized hash of each pair + * @param[in] children The left and right input of each pair, 2*n + * bytes per pair, contiguous + * @param[in,out] addrs Per pair, the address of the hash function + * call. The key/mask mode is modified. + * @param[in] seed The public seed + * @param[in] hash Instance of XMSS_Hash, that may only be used by the + * thread executing randomize_tree_hashes. + * @param[in] element_size Size of each node in bytes, the parameter "n" + **/ + static void randomize_tree_hashes(std::span out, + std::span children, + std::span addrs, + std::span seed, + XMSS_Hash& hash, + size_t element_size); + /** * Algorithm 8: "ltree" * Create an L-tree used to compute the leaves of the binary hash tree. diff --git a/src/lib/pubkey/xmss/xmss_parameters.h b/src/lib/pubkey/xmss/xmss_parameters.h index c8bf0c4070f..779b5b8ccd6 100644 --- a/src/lib/pubkey/xmss/xmss_parameters.h +++ b/src/lib/pubkey/xmss/xmss_parameters.h @@ -224,14 +224,36 @@ class BOTAN_PUBLIC_API(2, 0) XMSS_Parameters final { **/ size_t estimated_strength() const { return 8 * m_element_size; } - size_t raw_public_key_size() const { return sizeof(uint32_t) + 2 * element_size(); } + BOTAN_DEPRECATED("Deprecated without replacement") size_t raw_public_key_size() const { + return _raw_public_key_size(); + } + + BOTAN_DEPRECATED("This is no longer accurate and will be removed") size_t raw_legacy_private_key_size() const { + return _raw_legacy_private_key_size(); + } + + BOTAN_DEPRECATED("This is no longer accurate and will be removed") size_t raw_private_key_size() const { + return _raw_private_key_size(); + } + + /** + * Size of the encoded public key. For internal use only. + */ + size_t _raw_public_key_size() const { return sizeof(uint32_t) + 2 * element_size(); } - size_t raw_legacy_private_key_size() const { - return raw_public_key_size() + sizeof(uint32_t) + 2 * element_size(); + /** + * Size of a private key created by Botan 2. For internal use only. + */ + size_t _raw_legacy_private_key_size() const { + return _raw_public_key_size() + sizeof(uint32_t) + 2 * element_size(); } - size_t raw_private_key_size() const { - return raw_legacy_private_key_size() + 1 /* identifier for WOTS+ key derivation method */; + /** + * Size of the private key fields up to and including the WOTS+ key + * derivation method. For internal use only. + */ + size_t _raw_private_key_size() const { + return _raw_legacy_private_key_size() + 1 /* identifier for WOTS+ key derivation method */; } bool operator==(const XMSS_Parameters& p) const { return m_oid == p.m_oid; } diff --git a/src/lib/pubkey/xmss/xmss_privatekey.cpp b/src/lib/pubkey/xmss/xmss_privatekey.cpp index cd7867e6a26..019e42e9fe3 100644 --- a/src/lib/pubkey/xmss/xmss_privatekey.cpp +++ b/src/lib/pubkey/xmss/xmss_privatekey.cpp @@ -19,37 +19,88 @@ #include #include -#include +#include #include #include #include #include #include #include +#include #include #include #include #include #include +#include +#include +#include +#include namespace Botan { namespace { -// fall back to raw decoding for previous versions, which did not encode an OCTET STRING -secure_vector extract_raw_private_key(std::span key_bits, const XMSS_Parameters& xmss_params) { - secure_vector raw_key; - - // The public part of the input key bits was already parsed, so we can - // decide depending on the buffer length whether this must be BER decoded. - if(key_bits.size() == xmss_params.raw_private_key_size() || - key_bits.size() == xmss_params.raw_legacy_private_key_size()) { - raw_key.assign(key_bits.begin(), key_bits.end()); +/** + * Tag of a section holding the lowest row of the treetop + */ +constexpr uint32_t XMSS_SECTION_TREETOP = 1; + +enum class XMSS_PrivateKey_Format : uint8_t { + /** The fields up to the WOTS+ derivation method only, wrapped in an OCTET STRING (OID XMSS) */ + // TODO(Botan4) Remove the legacy format + Legacy, + /** Additionally the cached tree data (OID XMSS-Private-Key) */ + Current, + /** Raw bytes, which carry no OID: either of the above */ + // TODO(Botan4) Remove; raw bytes are then always in the current format + Either, +}; + +XMSS_PrivateKey_Format private_key_format(const AlgorithmIdentifier& alg_id) { + if(!alg_id.parameters_are_empty()) { + throw Decoding_Error("Unexpected parameters for XMSS private key"); + } + + // TODO(Botan4) Remove the legacy format, and accept only the current one + const auto& oid = alg_id.oid(); + if(oid.empty()) { + return XMSS_PrivateKey_Format::Either; + } else if(oid == OID::from_string("XMSS")) { + return XMSS_PrivateKey_Format::Legacy; + } else if(oid == OID::from_string("XMSS-Private-Key")) { + return XMSS_PrivateKey_Format::Current; } else { - BER_Decoder(key_bits, BER_Decoder::Limits::DER()).decode(raw_key, ASN1_Type::OctetString).verify_end(); + throw Decoding_Error("Unexpected OID for XMSS private key"); } +} - return raw_key; +// The raw key starts with the OID of the XMSS parameters, so its first byte is never 0x04 +bool is_wrapped_in_octet_string(std::span key_bits) { + return !key_bits.empty() && key_bits[0] == static_cast(ASN1_Type::OctetString); +} + +// TODO(Botan4) Remove the legacy format +bool is_legacy_encoding(std::span key_bits) { + if(is_wrapped_in_octet_string(key_bits)) { + return true; + } + if(key_bits.size() < sizeof(uint32_t)) { + throw Decoding_Error("Invalid XMSS private key size"); + } + const auto params = + XMSS_Parameters::from_id(static_cast(load_be(key_bits.data(), 0))); + return key_bits.size() == params._raw_private_key_size() || key_bits.size() == params._raw_legacy_private_key_size(); +} + +// fall back to raw decoding for previous versions, which did not encode an OCTET STRING +secure_vector extract_raw_legacy_private_key(std::span key_bits) { + if(is_wrapped_in_octet_string(key_bits)) { + secure_vector raw_key; + BER_Decoder(key_bits, BER_Decoder::Limits::DER()).decode(raw_key, ASN1_Type::OctetString).verify_end(); + return raw_key; + } + return secure_vector(key_bits.begin(), key_bits.end()); } bool is_known_wots_derivation_method(WOTS_Derivation_Method method) { @@ -77,90 +128,255 @@ Stateful_Key_Index_Registry::KeyId xmss_key_id(const XMSS_Parameters& params, derivation_uses_public_seed ? public_seed : std::span()); } +struct XMSS_Encoded_Private_Key { + XMSS_Parameters::xmss_algorithm_t oid; + WOTS_Derivation_Method wots_derivation_method; + secure_vector root; + secure_vector public_seed; + secure_vector private_seed; + secure_vector prf; + size_t unused_leaf; + std::optional> treetop_row; +}; + +XMSS_Encoded_Private_Key decode_private_key(const AlgorithmIdentifier& alg_id, std::span key_bits) { + const auto format = private_key_format(alg_id); + + // TODO(Botan4) Remove the legacy format + const bool legacy = format == XMSS_PrivateKey_Format::Legacy || + (format == XMSS_PrivateKey_Format::Either && is_legacy_encoding(key_bits)); + + const secure_vector raw_key = + legacy ? extract_raw_legacy_private_key(key_bits) : secure_vector(key_bits.begin(), key_bits.end()); + + BufferSlicer s(raw_key); + + const auto take = [&](size_t len) { + if(s.remaining() < len) { + throw Decoding_Error("Invalid XMSS private key size"); + } + return s.take(len); + }; + const auto take_u32 = [&]() { return load_be(take(sizeof(uint32_t)).first()); }; + const auto copy = [&](size_t len) { + const auto bytes = take(len); + return secure_vector(bytes.begin(), bytes.end()); + }; + + const auto oid = static_cast(take_u32()); + const auto params = XMSS_Parameters::from_id(oid); + const size_t n = params.element_size(); + + if(legacy && raw_key.size() != params._raw_private_key_size() && + raw_key.size() != params._raw_legacy_private_key_size()) { + throw Decoding_Error("Invalid XMSS private key size"); + } + + auto root = copy(n); + auto public_seed = copy(n); + const size_t unused_leaf = take_u32(); + auto prf = copy(n); + auto private_seed = copy(n); + + // Legacy keys generated prior to Botan 3.x don't feature a + // WOTS+ key derivation method encoded in their private key. + const auto wots_derivation_method = + (legacy && s.empty()) ? WOTS_Derivation_Method::Botan2x : static_cast(take(1)[0]); + + if(!is_known_wots_derivation_method(wots_derivation_method)) { + throw Decoding_Error("XMSS private key has an unknown WOTS+ derivation method"); + } + + std::optional> treetop_row; + + if(!legacy) { + const uint32_t sections = take_u32(); + for(uint32_t i = 0; i != sections; ++i) { + const uint32_t tag = take_u32(); + const uint32_t length = take_u32(); + const auto body = take(length); + + // Sections with unknown tags are skipped, for forward compatibility + if(tag == XMSS_SECTION_TREETOP) { + if(treetop_row.has_value()) { + throw Decoding_Error("XMSS private key contains more than one cached tree"); + } + if(length != Merkle_Treetop::row_size(static_cast(params.tree_height()), n)) { + throw Decoding_Error("Invalid size of cached tree in XMSS private key"); + } + treetop_row.emplace(body.begin(), body.end()); + } + } + } + + if(!s.empty()) { + throw Decoding_Error("XMSS private key contains more bytes than expected"); + } + + return XMSS_Encoded_Private_Key{oid, + wots_derivation_method, + std::move(root), + std::move(public_seed), + std::move(private_seed), + std::move(prf), + unused_leaf, + std::move(treetop_row)}; +} + } // namespace class XMSS_PrivateKey_Internal final { public: XMSS_PrivateKey_Internal(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, WOTS_Derivation_Method wots_derivation_method, - std::span public_seed, + secure_vector root, + secure_vector public_seed, secure_vector private_seed, secure_vector prf) : m_xmss_params(XMSS_Parameters::from_id(xmss_algo_id)), m_wots_params(m_xmss_params.wots_parameters()), m_wots_derivation_method(wots_derivation_method), + m_root(std::move(root)), + m_public_seed(std::move(public_seed)), m_prf(std::move(prf)), m_private_seed(std::move(private_seed)), - m_keyid(xmss_key_id(m_xmss_params, m_wots_derivation_method, m_private_seed, public_seed)) { + m_keyid(xmss_key_id(m_xmss_params, m_wots_derivation_method, m_private_seed, m_public_seed)) { // Callers update the registry afterwards, so all validation must happen here BOTAN_ARG_CHECK(is_known_wots_derivation_method(m_wots_derivation_method), "XMSS: unknown WOTS+ derivation method"); + BOTAN_ARG_CHECK(m_root.size() == m_xmss_params.element_size(), "XMSS: unexpected byte length of root hash"); + BOTAN_ARG_CHECK(m_public_seed.size() == m_xmss_params.element_size(), + "XMSS: unexpected byte length of public seed"); BOTAN_ARG_CHECK(m_prf.size() == m_xmss_params.element_size(), "XMSS: unexpected byte length of PRF value"); BOTAN_ARG_CHECK(m_private_seed.size() == m_xmss_params.element_size(), "XMSS: unexpected byte length of private seed"); } - XMSS_PrivateKey_Internal(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, std::span key_bits) : - m_xmss_params(XMSS_Parameters::from_id(xmss_algo_id)), m_wots_params(m_xmss_params.wots_parameters()) { - /* - The code requires sizeof(size_t) >= ceil(tree_height / 8) + XMSS_PrivateKey_Internal(const AlgorithmIdentifier& alg_id, std::span key_bits) : + XMSS_PrivateKey_Internal(decode_private_key(alg_id, key_bits)) {} - Maximum supported tree height is 20, ceil(20/8) == 3, so 4 byte - size_t is sufficient for all defined parameters, or even a - (hypothetical) tree height 32, which would be extremely slow to - compute. - */ - static_assert(sizeof(size_t) >= 4, "size_t is big enough to support leaf index"); + XMSS_PrivateKey_Internal(const XMSS_PrivateKey_Internal& other) = delete; + XMSS_PrivateKey_Internal(XMSS_PrivateKey_Internal&& other) = delete; + XMSS_PrivateKey_Internal& operator=(const XMSS_PrivateKey_Internal& other) = delete; + XMSS_PrivateKey_Internal& operator=(XMSS_PrivateKey_Internal&& other) = delete; + ~XMSS_PrivateKey_Internal() = default; + + static std::shared_ptr generate(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, + RandomNumberGenerator& rng, + WOTS_Derivation_Method wots_derivation_method) { + BOTAN_ARG_CHECK(is_known_wots_derivation_method(wots_derivation_method), + "XMSS: unknown WOTS+ derivation method"); - const secure_vector raw_key = extract_raw_private_key(key_bits, m_xmss_params); + const auto params = XMSS_Parameters::from_id(xmss_algo_id); + const size_t n = params.element_size(); + + // The order in which the seeds are drawn from the RNG (public seed, then + // prf, then private seed) must match the historical two-phase construction + // so that a deterministic RNG reproduces the same key material. + auto public_seed = rng.random_vec(n); + auto prf = rng.random_vec(n); + auto private_seed = rng.random_vec(n); + + XMSS_Hash hash(params); + const XMSS_Tree_Builder builder(params.wots_parameters(), wots_derivation_method, public_seed, private_seed); + auto [treetop, subtree] = builder.merkle_tree(params.tree_height(), XMSS_Address(), hash).build(0); + const auto root_bytes = treetop.root(); + secure_vector root(root_bytes.begin(), root_bytes.end()); + + auto sk = std::make_shared(xmss_algo_id, + wots_derivation_method, + std::move(root), + std::move(public_seed), + std::move(private_seed), + std::move(prf)); + sk->m_nodes = {std::make_shared(std::move(treetop)), + std::make_shared(std::move(subtree))}; + return sk; + } - if(raw_key.size() != m_xmss_params.raw_private_key_size() && - raw_key.size() != m_xmss_params.raw_legacy_private_key_size()) { - throw Decoding_Error("Invalid XMSS private key size"); + secure_vector serialize() const { + const auto treetop = [this] { + const lock_guard_type lock(m_cache_mutex); + return m_nodes.treetop; + }(); + + const auto oid = store_be(static_cast(m_xmss_params.oid())); + const auto unused_index = store_be(checked_cast_to(unused_leaf_index())); + const std::array wots_derivation_method{static_cast(m_wots_derivation_method)}; + + if(treetop == nullptr) { + return concat>(oid, + m_root, + m_public_seed, + unused_index, + m_prf, + m_private_seed, + wots_derivation_method, + store_be(uint32_t(0))); } - BufferSlicer s(raw_key); + const auto row = treetop->row(); + return concat>(oid, + m_root, + m_public_seed, + unused_index, + m_prf, + m_private_seed, + wots_derivation_method, + store_be(uint32_t(1)), + store_be(XMSS_SECTION_TREETOP), + store_be(checked_cast_to(row.size())), + row); + } + + size_t reserve_leaf(std::span auth_path, XMSS_Hash& hash) const { + size_t idx = 0; + Tree_Nodes cached; + + { + const lock_guard_type lock(m_cache_mutex); - // The OID and root were already parsed by XMSS_PublicKey; the public - // seed is needed here as part of the key identity - s.skip(4 + m_xmss_params.element_size()); - const auto public_seed = s.take(m_xmss_params.element_size()); + // Reserving the index while holding the lock means the cache of this + // object only ever moves forward, even when signing concurrently + idx = reserve_unused_leaf_index(); + cached = m_nodes; + } - const auto unused_leaf_bytes = s.take(sizeof(uint32_t)); - const size_t unused_leaf = load_be(unused_leaf_bytes.data(), 0); + const auto q = static_cast(idx); + auto nodes = cached; - m_prf = s.copy_as_secure_vector(m_xmss_params.element_size()); - m_private_seed = s.copy_as_secure_vector(m_xmss_params.element_size()); + if(!has_nodes_for_leaf(nodes, q)) { + // Computing nodes may wait on threads which are themselves signing + // with this key, so it must not happen while holding the lock + nodes = compute_nodes(cached.treetop, q, hash); - // Legacy keys generated prior to Botan 3.x don't feature a - // WOTS+ key derivation method encoded in their private key. - m_wots_derivation_method = - (s.empty()) ? WOTS_Derivation_Method::Botan2x : static_cast(s.take_byte()); + const lock_guard_type lock(m_cache_mutex); - if(!is_known_wots_derivation_method(m_wots_derivation_method)) { - throw Decoding_Error("XMSS private key has an unknown WOTS+ derivation method"); + // Unless another signature updated or discarded the cache meanwhile + if(m_nodes.treetop == cached.treetop && m_nodes.subtree == cached.subtree) { + m_nodes = nodes; + } } - BOTAN_ASSERT_NOMSG(s.empty()); + nodes.treetop->auth_path(auth_path, q, nodes.subtree.get()); + return idx; + } - m_keyid = xmss_key_id(m_xmss_params, m_wots_derivation_method, m_private_seed, public_seed); + void discard_cached_tree() const { + const lock_guard_type lock(m_cache_mutex); + m_nodes = {}; + } - // Note m_keyid must be initialized before set_unused_leaf_index is called! - // This comes last, after every check that can reject the encoding, since - // it raises the index lower bound shared by all copies of this key. - set_unused_leaf_index(unused_leaf); + bool root_matches_seed() const { + XMSS_Hash hash(m_xmss_params); + return std::ranges::equal(merkle_tree(hash).root(), m_root); } - secure_vector serialize(std::vector raw_public_key) const { - std::vector unused_index(4); - store_be(checked_cast_to(unused_leaf_index()), unused_index.data()); + const XMSS_Parameters& xmss_parameters() const { return m_xmss_params; } - std::vector wots_derivation_method; - wots_derivation_method.push_back(static_cast(m_wots_derivation_method)); + const secure_vector& root() const { return m_root; } - return concat>( - raw_public_key, unused_index, m_prf, m_private_seed, wots_derivation_method); - } + const secure_vector& public_seed() const { return m_public_seed; } const secure_vector& prf_value() const { return m_prf; } @@ -182,6 +398,63 @@ class XMSS_PrivateKey_Internal final { } } + size_t unused_leaf_index() const { + const uint64_t idx = Stateful_Key_Index_Registry::global().current_index(m_keyid); + return checked_cast_to(idx); + } + + uint64_t remaining_signatures() const { + return Stateful_Key_Index_Registry::global().remaining_operations(m_keyid); + } + + private: + /** + * The public tree nodes needed for signing; the subtree is the one + * containing the most recently reserved leaf + */ + struct Tree_Nodes final { + std::shared_ptr treetop; + std::shared_ptr subtree; + }; + + /** + * True if @p nodes are the ones needed to sign with leaf @p q + */ + static bool has_nodes_for_leaf(const Tree_Nodes& nodes, uint32_t q) { + if(nodes.treetop == nullptr) { + return false; + } + // When k is zero the treetop is the whole tree + const uint32_t k = nodes.treetop->k(); + return k == 0 || (nodes.subtree != nullptr && nodes.subtree->index() == (q >> k)); + } + + explicit XMSS_PrivateKey_Internal(XMSS_Encoded_Private_Key encoded) : + XMSS_PrivateKey_Internal(encoded.oid, + encoded.wots_derivation_method, + std::move(encoded.root), + std::move(encoded.public_seed), + std::move(encoded.private_seed), + std::move(encoded.prf)) { + /* + The code requires sizeof(size_t) >= ceil(tree_height / 8) + + Maximum supported tree height is 20, ceil(20/8) == 3, so 4 byte + size_t is sufficient for all defined parameters, or even a + (hypothetical) tree height 32, which would be extremely slow to + compute. + */ + static_assert(sizeof(size_t) >= 4, "size_t is big enough to support leaf index"); + + if(encoded.treetop_row.has_value()) { + adopt_encoded_row(encoded.treetop_row.value()); + } + + // This comes last, after every check that can reject the encoding, since + // it raises the index lower bound shared by all copies of this key. + set_unused_leaf_index(encoded.unused_leaf); + } + size_t reserve_unused_leaf_index() const { const auto idx = Stateful_Key_Index_Registry::global().reserve_next_index(m_keyid); if(!idx.has_value()) { @@ -191,78 +464,73 @@ class XMSS_PrivateKey_Internal final { return static_cast(idx.value()); } - size_t unused_leaf_index() const { - const uint64_t idx = Stateful_Key_Index_Registry::global().current_index(m_keyid); - return checked_cast_to(idx); + Merkle_Tree_Builder merkle_tree(XMSS_Hash& hash) const { + return XMSS_Tree_Builder(m_wots_params, m_wots_derivation_method, m_public_seed, m_private_seed) + .merkle_tree(m_xmss_params.tree_height(), XMSS_Address(), hash); } - uint64_t remaining_signatures() const { - return Stateful_Key_Index_Registry::global().remaining_operations(m_keyid); + /** + * Keep the treetop read from an encoding if it matches the root + */ + void adopt_encoded_row(std::span row) { + XMSS_Hash hash(m_xmss_params); + auto treetop = merkle_tree(hash).treetop_from_row(row); + if(std::ranges::equal(treetop.root(), m_root)) { + m_nodes.treetop = std::make_shared(std::move(treetop)); + } + } + + /** + * Compute the nodes needed to sign with leaf @p q + * + * @param treetop The treetop to compute the subtree for, or null to + * compute the whole tree + */ + Tree_Nodes compute_nodes(const std::shared_ptr& treetop, + uint32_t q, + XMSS_Hash& hash) const { + const auto tree = merkle_tree(hash); + + if(treetop != nullptr) { + if(auto subtree = tree.build_subtree(*treetop, q)) { + return {treetop, std::make_shared(std::move(subtree.value()))}; + } + // The loaded treetop did not match the seed; start over from the seed alone + } + + auto [top, sub] = tree.build(q); + if(!std::ranges::equal(top.root(), m_root)) { + throw Invalid_State("XMSS private key does not match its public key"); + } + return {std::make_shared(std::move(top)), + std::make_shared(std::move(sub))}; } - private: XMSS_Parameters m_xmss_params; XMSS_WOTS_Parameters m_wots_params; WOTS_Derivation_Method m_wots_derivation_method; + secure_vector m_root; + secure_vector m_public_seed; secure_vector m_prf; secure_vector m_private_seed; Stateful_Key_Index_Registry::KeyId m_keyid; + + // The nodes are immutable, and only replaced while holding the mutex + mutable mutex_type m_cache_mutex; + mutable Tree_Nodes m_nodes; }; XMSS_PrivateKey::XMSS_PrivateKey(std::span key_bits) : XMSS_PrivateKey(AlgorithmIdentifier(), key_bits) {} XMSS_PrivateKey::XMSS_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : - XMSS_PublicKey(alg_id, key_bits, Key_Encoding::PrivateKey), - m_private(std::make_shared(xmss_parameters().oid(), key_bits)) {} - -struct XMSS_PrivateKey::Keygen_Material { - secure_vector private_seed; - secure_vector prf; - secure_vector public_seed; - secure_vector root; -}; - -XMSS_PrivateKey::Keygen_Material XMSS_PrivateKey::generate_keygen_material( - XMSS_Parameters::xmss_algorithm_t xmss_algo_id, - RandomNumberGenerator& rng, - WOTS_Derivation_Method wots_derivation_method) { - BOTAN_ARG_CHECK(is_known_wots_derivation_method(wots_derivation_method), "XMSS: unknown WOTS+ derivation method"); - - const auto params = XMSS_Parameters::from_id(xmss_algo_id); - const size_t n = params.element_size(); - - // The order in which the seeds are drawn from the RNG (public seed, then - // prf, then private seed) must match the historical two-phase construction - // so that a deterministic RNG reproduces the same key material. - auto public_seed = rng.random_vec(n); - auto prf = rng.random_vec(n); - auto private_seed = rng.random_vec(n); - - const XMSS_Address adrs; - XMSS_Hash hash(params); - const XMSS_Tree_Builder builder(params.wots_parameters(), wots_derivation_method, public_seed, private_seed); - auto root = builder.tree_hash(0, params.tree_height(), adrs, hash); - - return Keygen_Material{std::move(private_seed), std::move(prf), std::move(public_seed), std::move(root)}; -} + XMSS_PrivateKey(std::make_shared(alg_id, key_bits)) {} XMSS_PrivateKey::XMSS_PrivateKey(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, RandomNumberGenerator& rng, WOTS_Derivation_Method wots_derivation_method) : - XMSS_PrivateKey( - xmss_algo_id, wots_derivation_method, generate_keygen_material(xmss_algo_id, rng, wots_derivation_method)) {} - -XMSS_PrivateKey::XMSS_PrivateKey(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, - WOTS_Derivation_Method wots_derivation_method, - Keygen_Material material) : - XMSS_PublicKey(xmss_algo_id, std::move(material.root), std::move(material.public_seed)), - m_private(std::make_shared(xmss_algo_id, - wots_derivation_method, - this->public_seed(), - std::move(material.private_seed), - std::move(material.prf))) {} + XMSS_PrivateKey(XMSS_PrivateKey_Internal::generate(xmss_algo_id, rng, wots_derivation_method)) {} XMSS_PrivateKey::XMSS_PrivateKey(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, size_t idx_leaf, @@ -271,32 +539,27 @@ XMSS_PrivateKey::XMSS_PrivateKey(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, secure_vector root, secure_vector public_seed, WOTS_Derivation_Method wots_derivation_method) : - XMSS_PublicKey(xmss_algo_id, std::move(root), std::move(public_seed)), - m_private(std::make_shared( - xmss_algo_id, wots_derivation_method, this->public_seed(), std::move(wots_priv_seed), std::move(prf))) { + XMSS_PrivateKey(std::make_shared(xmss_algo_id, + wots_derivation_method, + std::move(root), + std::move(public_seed), + std::move(wots_priv_seed), + std::move(prf))) { m_private->set_unused_leaf_index(idx_leaf); } +XMSS_PrivateKey::XMSS_PrivateKey(std::shared_ptr sk) : + XMSS_PublicKey(sk->xmss_parameters().oid(), sk->root(), sk->public_seed()), m_private(std::move(sk)) {} + bool XMSS_PrivateKey::check_key(RandomNumberGenerator& /*rng*/, bool strong) const { if(strong) { // Check that the stored root is consistent with the seeds by // recomputing it. This costs about as much as a key generation. - const XMSS_Address adrs; - XMSS_Hash hash(xmss_parameters()); - return tree_hash(0, xmss_parameters().tree_height(), adrs, hash) == root(); + return m_private->root_matches_seed(); } return true; } -secure_vector XMSS_PrivateKey::tree_hash(size_t start_idx, - size_t target_node_height, - const XMSS_Address& adrs, - XMSS_Hash& hash) const { - return XMSS_Tree_Builder( - xmss_parameters().wots_parameters(), wots_derivation_method(), public_seed(), m_private->private_seed()) - .tree_hash(start_idx, target_node_height, adrs, hash); -} - XMSS_WOTS_PrivateKey XMSS_PrivateKey::wots_private_key_for(const XMSS_Address& adrs, XMSS_Hash& hash) const { return XMSS_Tree_Builder( xmss_parameters().wots_parameters(), wots_derivation_method(), public_seed(), m_private->private_seed()) @@ -304,11 +567,20 @@ XMSS_WOTS_PrivateKey XMSS_PrivateKey::wots_private_key_for(const XMSS_Address& a } secure_vector XMSS_PrivateKey::private_key_bits() const { - return DER_Encoder().encode(raw_private_key(), ASN1_Type::OctetString).get_contents(); + return raw_private_key(); +} + +AlgorithmIdentifier XMSS_PrivateKey::pkcs8_algorithm_identifier() const { + // The format of the private key is not standardized, so it gets its own OID + return AlgorithmIdentifier(OID::from_string("XMSS-Private-Key"), AlgorithmIdentifier::USE_EMPTY_PARAM); +} + +size_t XMSS_PrivateKey::reserve_leaf(std::span auth_path, XMSS_Hash& hash) const { + return m_private->reserve_leaf(auth_path, hash); } -size_t XMSS_PrivateKey::reserve_unused_leaf_index() { - return m_private->reserve_unused_leaf_index(); +void XMSS_PrivateKey::discard_cached_tree() const { + m_private->discard_cached_tree(); } size_t XMSS_PrivateKey::unused_leaf_index() const { @@ -328,7 +600,7 @@ const secure_vector& XMSS_PrivateKey::prf_value() const { } secure_vector XMSS_PrivateKey::raw_private_key() const { - return m_private->serialize(raw_public_key()); + return m_private->serialize(); } WOTS_Derivation_Method XMSS_PrivateKey::wots_derivation_method() const { diff --git a/src/lib/pubkey/xmss/xmss_publickey.cpp b/src/lib/pubkey/xmss/xmss_publickey.cpp index 6b1bd77ea9b..036f03342fa 100644 --- a/src/lib/pubkey/xmss/xmss_publickey.cpp +++ b/src/lib/pubkey/xmss/xmss_publickey.cpp @@ -54,8 +54,8 @@ std::vector extract_raw_public_key(std::span key_bits) { // and they might be either a sole public key or a concatenation of public // and private key (with the optional WOTS+ derivation identifier). const XMSS_Parameters params = XMSS_Parameters::from_id(deserialize_xmss_oid(raw_key)); - if(raw_key.size() != params.raw_public_key_size() && raw_key.size() != params.raw_private_key_size() && - raw_key.size() != params.raw_legacy_private_key_size()) { + if(raw_key.size() != params._raw_public_key_size() && raw_key.size() != params._raw_private_key_size() && + raw_key.size() != params._raw_legacy_private_key_size()) { throw Decoding_Error("unpacked XMSS key does not have the correct length"); } } catch(Decoding_Error&) { @@ -123,11 +123,11 @@ XMSS_PublicKey::XMSS_PublicKey(const AlgorithmIdentifier& alg_id, const auto params = XMSS_Parameters::from_id(xmss_oid); if(encoding == Key_Encoding::PublicKey) { - if(raw_key.size() != params.raw_public_key_size()) { + if(raw_key.size() != params._raw_public_key_size()) { throw Decoding_Error("Invalid XMSS public key size detected"); } - } else if(raw_key.size() != params.raw_private_key_size() && - raw_key.size() != params.raw_legacy_private_key_size()) { + } else if(raw_key.size() != params._raw_private_key_size() && + raw_key.size() != params._raw_legacy_private_key_size()) { throw Decoding_Error("Invalid XMSS private key size"); } diff --git a/src/lib/pubkey/xmss/xmss_signature_operation.cpp b/src/lib/pubkey/xmss/xmss_signature_operation.cpp index 21d07f184ce..cd2ac08ca48 100644 --- a/src/lib/pubkey/xmss/xmss_signature_operation.cpp +++ b/src/lib/pubkey/xmss/xmss_signature_operation.cpp @@ -22,7 +22,7 @@ namespace Botan { XMSS_Signature_Operation::XMSS_Signature_Operation(const XMSS_PrivateKey& private_key) : - m_priv_key(private_key), m_hash(private_key.xmss_parameters()) {} + m_priv_key(private_key), m_hash(private_key.xmss_parameters()), m_verifier(private_key) {} size_t XMSS_Signature_Operation::signature_length() const { const auto& params = m_priv_key.xmss_parameters(); @@ -40,10 +40,12 @@ std::vector XMSS_Signature_Operation::sign(RandomNumberGenerator& /*rng const std::vector msg = std::exchange(m_msg_buffer, {}); const auto& params = m_priv_key.xmss_parameters(); + const size_t n = params.element_size(); // reserve leaf index so it can not be reused by another signature // operation using the same private key. - const auto leaf_idx = static_cast(m_priv_key.reserve_unused_leaf_index()); + std::vector auth_path_bytes(params.tree_height() * n); + const auto leaf_idx = static_cast(m_priv_key.reserve_leaf(auth_path_bytes, m_hash)); secure_vector index_bytes; secure_vector randomness; @@ -59,15 +61,12 @@ std::vector XMSS_Signature_Operation::sign(RandomNumberGenerator& /*rng const auto msg_hash = m_hash.h_msg_final(); wots_keysig_t auth_path(params.tree_height()); - - XMSS_Address adrs; - adrs.set_type(XMSS_Address::Type::Hash_Tree_Address); - for(size_t j = 0; j < params.tree_height(); j++) { - const size_t k = (leaf_idx / (static_cast(1) << j)) ^ 0x01; - auth_path[j] = m_priv_key.tree_hash(k * (static_cast(1) << j), j, adrs, m_hash); + const auto node = std::span(auth_path_bytes).subspan(j * n, n); + auth_path[j].assign(node.begin(), node.end()); } + XMSS_Address adrs; adrs.set_type(XMSS_Address::Type::OTS_Hash_Address); adrs.set_ots_address(leaf_idx); @@ -77,7 +76,15 @@ std::vector XMSS_Signature_Operation::sign(RandomNumberGenerator& /*rng m_priv_key.wots_private_key_for(adrs, m_hash).sign(msg_hash, m_priv_key.public_seed(), adrs, m_hash); const XMSS_Signature sig(leaf_idx, randomness, tree_sig); - return sig.bytes(); + auto sig_bytes = sig.bytes(); + + if(!m_verifier.is_valid_signature_of(msg, sig_bytes)) { + // Discard the cache so the next signature is computed from the seed alone + m_priv_key.discard_cached_tree(); + throw Internal_Error("XMSS signature failed verification"); + } + + return sig_bytes; } AlgorithmIdentifier XMSS_Signature_Operation::algorithm_identifier() const { diff --git a/src/lib/pubkey/xmss/xmss_signature_operation.h b/src/lib/pubkey/xmss/xmss_signature_operation.h index 5468eda03f0..c9dafc62100 100644 --- a/src/lib/pubkey/xmss/xmss_signature_operation.h +++ b/src/lib/pubkey/xmss/xmss_signature_operation.h @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace Botan { @@ -49,6 +50,8 @@ class XMSS_Signature_Operation final : public virtual PK_Ops::Signature { private: XMSS_PrivateKey m_priv_key; XMSS_Hash m_hash; + // Checks each signature before it is released + XMSS_Verification_Operation m_verifier; std::vector m_msg_buffer; }; diff --git a/src/lib/pubkey/xmss/xmss_tree_builder.cpp b/src/lib/pubkey/xmss/xmss_tree_builder.cpp index 88693da0994..e1f70e4f44d 100644 --- a/src/lib/pubkey/xmss/xmss_tree_builder.cpp +++ b/src/lib/pubkey/xmss/xmss_tree_builder.cpp @@ -13,7 +13,6 @@ #include #include #include -#include namespace Botan { @@ -23,60 +22,37 @@ namespace { * Number of leaves whose WOTS+ keys and L-trees are computed at once, * so that the hash calls of each step are batched across all of them */ -constexpr size_t LEAF_BATCH = 128; +constexpr uint32_t LEAF_BATCH = 128; } // namespace -secure_vector XMSS_Tree_Builder::tree_hash(size_t start_idx, - size_t target_node_height, - const XMSS_Address& adrs_in, - XMSS_Hash& hash) const { - BOTAN_ASSERT_NOMSG(target_node_height <= 30); - BOTAN_ASSERT((start_idx % (static_cast(1) << target_node_height)) == 0, - "Start index must be divisible by 2^{target node height}."); +Merkle_Tree_Builder XMSS_Tree_Builder::merkle_tree(size_t height, const XMSS_Address& adrs, XMSS_Hash& hash) const { + BOTAN_ASSERT_NOMSG(height <= 30); const size_t n = m_wots_params.element_size(); - const secure_vector& seed = this->public_seed(); - const size_t last_idx = (static_cast(1) << target_node_height) + start_idx; - const size_t batch = std::min(LEAF_BATCH, last_idx - start_idx); - secure_vector leaves(batch * n); - - // node stack, holds all nodes on stack and one extra "pending" node. This - // temporary node referred to as "node" in the XMSS standard document stays - // a pending element, meaning it is not regarded as element on the stack - // until level is increased. - std::vector> nodes(target_node_height + 1, secure_vector(n)); - std::vector node_levels(target_node_height + 1); - - uint8_t level = 0; // current level on the node stack. - - XMSS_Address adrs(adrs_in); - adrs.set_type(XMSS_Address::Type::Hash_Tree_Address); - - for(size_t i = start_idx; i < last_idx; i++) { - const size_t b = (i - start_idx) % batch; - if(b == 0) { - const size_t count = std::min(batch, last_idx - i); - compute_leaves(std::span(leaves).first(count * n), i, count, adrs, hash); - } - - copy_mem(nodes[level], std::span(leaves).subspan(b * n, n)); - node_levels[level] = 0; + auto leaf_fn = [builder = *this, adrs, &hash](std::span out, uint32_t first_leaf, uint32_t count) { + builder.compute_leaves(out, first_leaf, count, adrs, hash); + }; + + // Algorithm 9: "treeHash", which addresses a node by the height of its + // children and its own index + auto node_fn = + [builder = *this, adrs, &hash, n]( + std::span out, uint32_t j, uint32_t first_t, uint32_t count, std::span children) { + XMSS_Address node_adrs(adrs); + node_adrs.set_type(XMSS_Address::Type::Hash_Tree_Address); + node_adrs.set_tree_height(j - 1); + + std::vector node_addrs(count, node_adrs); + for(uint32_t i = 0; i != count; ++i) { + node_addrs[i].set_tree_index(first_t + i); + } - adrs.set_tree_height(0); - adrs.set_tree_index(static_cast(i)); + XMSS_Common_Ops::randomize_tree_hashes(out, children, node_addrs, builder.public_seed(), hash, n); + }; - while(level > 0 && node_levels[level] == node_levels[level - 1]) { - adrs.set_tree_index(((adrs.get_tree_index() - 1) >> 1)); - XMSS_Common_Ops::randomize_tree_hash(nodes[level - 1], nodes[level - 1], nodes[level], adrs, seed, hash, n); - node_levels[level - 1]++; - level--; //Pop stack top element - adrs.set_tree_height(adrs.get_tree_height() + 1); - } - level++; //push temporary node to stack - } - return nodes[level - 1]; + return Merkle_Tree_Builder(static_cast(height), n, LEAF_BATCH, std::move(leaf_fn), std::move(node_fn)); } void XMSS_Tree_Builder::compute_leaves( @@ -122,7 +98,7 @@ void XMSS_Tree_Builder::wots_private_keys(std::span sks, const size_t len = m_wots_params.len(); const size_t count = addrs.size(); - BOTAN_ASSERT_NOMSG(sks.size() == count * n && count % len == 0); + BOTAN_ASSERT_NOMSG(len > 0 && sks.size() == count * n && count % len == 0); switch(m_wots_derivation_method) { case WOTS_Derivation_Method::NIST_SP800_208: { diff --git a/src/lib/pubkey/xmss/xmss_tree_builder.h b/src/lib/pubkey/xmss/xmss_tree_builder.h index 993dc8e0900..084df349773 100644 --- a/src/lib/pubkey/xmss/xmss_tree_builder.h +++ b/src/lib/pubkey/xmss/xmss_tree_builder.h @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -41,10 +42,12 @@ class XMSS_Tree_Builder final { m_public_seed(public_seed), m_private_seed(private_seed) {} - secure_vector tree_hash(size_t start_idx, - size_t target_node_height, - const XMSS_Address& adrs, - XMSS_Hash& hash) const; + /** + * The tree of height @p height at @p adrs + * + * The result refers to @p hash and to the seeds this object refers to. + */ + Merkle_Tree_Builder merkle_tree(size_t height, const XMSS_Address& adrs, XMSS_Hash& hash) const; XMSS_WOTS_PrivateKey wots_private_key_for(const XMSS_Address& adrs, XMSS_Hash& hash) const; diff --git a/src/lib/pubkey/xmss/xmss_verification_operation.cpp b/src/lib/pubkey/xmss/xmss_verification_operation.cpp index a6508364436..c81c969a94d 100644 --- a/src/lib/pubkey/xmss/xmss_verification_operation.cpp +++ b/src/lib/pubkey/xmss/xmss_verification_operation.cpp @@ -19,7 +19,7 @@ XMSS_Verification_Operation::XMSS_Verification_Operation(const XMSS_PublicKey& p m_pub_key(public_key), m_hash(public_key.xmss_parameters()), m_msg_buf(0) {} bool XMSS_Verification_Operation::verify(const XMSS_Signature& sig, - const secure_vector& msg, + std::span msg, const XMSS_PublicKey& public_key) { const auto& params = m_pub_key.xmss_parameters(); @@ -52,13 +52,16 @@ void XMSS_Verification_Operation::update(std::span input) { } bool XMSS_Verification_Operation::is_valid_signature(std::span sig) { + const bool result = is_valid_signature_of(m_msg_buf, sig); + m_msg_buf.clear(); + return result; +} + +bool XMSS_Verification_Operation::is_valid_signature_of(std::span msg, std::span sig) { try { const XMSS_Signature signature(m_pub_key.xmss_parameters().oid(), sig); - const bool result = verify(signature, m_msg_buf, m_pub_key); - m_msg_buf.clear(); - return result; + return verify(signature, msg, m_pub_key); } catch(...) { - m_msg_buf.clear(); return false; } } diff --git a/src/lib/pubkey/xmss/xmss_verification_operation.h b/src/lib/pubkey/xmss/xmss_verification_operation.h index 4dd6c1b7d0e..07a516e773c 100644 --- a/src/lib/pubkey/xmss/xmss_verification_operation.h +++ b/src/lib/pubkey/xmss/xmss_verification_operation.h @@ -25,6 +25,12 @@ class XMSS_Verification_Operation final : public virtual PK_Ops::Verification { bool is_valid_signature(std::span sign) override; + /** + * Verify a serialized signature of a message which the caller already + * holds, without buffering it. Any input given to update() is ignored. + */ + bool is_valid_signature_of(std::span msg, std::span sign); + void update(std::span input) override; std::string hash_function() const override { return m_hash.hash_function(); } @@ -40,7 +46,7 @@ class XMSS_Verification_Operation final : public virtual PK_Ops::Verification { * * @return true if signature sig is valid for msg, false otherwise. **/ - bool verify(const XMSS_Signature& sig, const secure_vector& msg, const XMSS_PublicKey& pub_key); + bool verify(const XMSS_Signature& sig, std::span msg, const XMSS_PublicKey& pub_key); const XMSS_PublicKey m_pub_key; XMSS_Hash m_hash; diff --git a/src/lib/utils/tree_hash/info.txt b/src/lib/utils/tree_hash/info.txt index d85a24cdf87..1ae99ced3e6 100644 --- a/src/lib/utils/tree_hash/info.txt +++ b/src/lib/utils/tree_hash/info.txt @@ -5,6 +5,7 @@ type -> "Internal" +merkle_tree.h tree_hash.h diff --git a/src/lib/utils/tree_hash/merkle_tree.cpp b/src/lib/utils/tree_hash/merkle_tree.cpp new file mode 100644 index 00000000000..f2c259868ea --- /dev/null +++ b/src/lib/utils/tree_hash/merkle_tree.cpp @@ -0,0 +1,229 @@ +/* + * Merkle trees with a stored treetop + * (C) 2026 Jack Lloyd + * + * Botan is released under the Simplified BSD License (see license.txt) + */ + +#include + +#include +#include +#include +#include +#include + +namespace Botan { + +uint32_t Merkle_Treetop::subtree_height(uint32_t h) { + constexpr uint32_t max_row_height = 10; + return h > max_row_height ? h - max_row_height : 0; +} + +size_t Merkle_Treetop::row_size(uint32_t h, size_t n) { + return (size_t(1) << (h - subtree_height(h))) * n; +} + +Merkle_Treetop::Merkle_Treetop(uint32_t h, size_t n, std::vector nodes) : + m_h(h), m_k(subtree_height(h)), m_n(n), m_nodes(std::move(nodes)) { + BOTAN_ASSERT_NOMSG(m_nodes.size() == (size_t(1) << (m_h - m_k + 1)) * m_n); +} + +Merkle_Treetop Merkle_Treetop::from_row(uint32_t h, + size_t n, + std::span row, + const Merkle_Node_Fn& node_fn) { + BOTAN_ARG_CHECK(h < 32, "Invalid Merkle tree height"); + BOTAN_ARG_CHECK(row.size() == row_size(h, n), "Invalid Merkle treetop row size"); + + const uint32_t k = subtree_height(h); + const size_t row_start = size_t(1) << (h - k); + + std::vector nodes(2 * row_start * n); + copy_mem(std::span(nodes).subspan(row_start * n), row); + + for(uint32_t j = k + 1; j <= h; ++j) { + // Each layer is directly followed by its children + const size_t layer_start = size_t(1) << (h - j); + node_fn(std::span(nodes).subspan(layer_start * n, layer_start * n), + j, + 0, + static_cast(layer_start), + std::span(nodes).subspan(2 * layer_start * n, 2 * layer_start * n)); + } + + return Merkle_Treetop(h, n, std::move(nodes)); +} + +std::span Merkle_Treetop::row() const { + return std::span(m_nodes).subspan((size_t(1) << (m_h - m_k)) * m_n); +} + +std::span Merkle_Treetop::node(uint32_t j, uint32_t t) const { + BOTAN_ASSERT_NOMSG(j >= m_k && j <= m_h && t < (uint32_t(1) << (m_h - j))); + const size_t pos = (size_t(1) << (m_h - j)) + t; + return std::span(m_nodes).subspan(pos * m_n, m_n); +} + +void Merkle_Treetop::auth_path(std::span out, uint32_t q, const Merkle_Subtree* subtree) const { + BOTAN_ARG_CHECK(out.size() == m_h * m_n, "Invalid authentication path buffer size"); + BOTAN_ARG_CHECK(q < (uint32_t(1) << m_h), "Invalid Merkle tree leaf index"); + BOTAN_ARG_CHECK(m_k == 0 || (subtree != nullptr && subtree->index() == (q >> m_k)), + "Subtree does not contain the leaf"); + + for(uint32_t j = 0; j != m_h; ++j) { + const uint32_t sibling = (q >> j) ^ 1; + const auto sibling_node = (j >= m_k) ? node(j, sibling) : subtree->node(j, sibling); + copy_mem(out.subspan(j * m_n, m_n), sibling_node); + } +} + +Merkle_Subtree::Merkle_Subtree(uint32_t k, uint32_t index, size_t n, std::vector nodes) : + m_k(k), m_index(index), m_n(n), m_nodes(std::move(nodes)) { + BOTAN_ASSERT_NOMSG(m_nodes.size() == (size_t(1) << (m_k + 1)) * m_n); +} + +std::span Merkle_Subtree::node(uint32_t j, uint32_t t) const { + BOTAN_ASSERT_NOMSG(j <= m_k && (t >> (m_k - j)) == m_index); + const uint32_t layer_start = uint32_t(1) << (m_k - j); + const size_t pos = layer_start + (t & (layer_start - 1)); + return std::span(m_nodes).subspan(pos * m_n, m_n); +} + +Merkle_Tree_Builder::Merkle_Tree_Builder( + uint32_t h, size_t n, uint32_t leaf_batch, Merkle_Leaf_Fn leaf_fn, Merkle_Node_Fn node_fn) : + m_h(h), m_n(n), m_leaf_batch(leaf_batch), m_leaf_fn(std::move(leaf_fn)), m_node_fn(std::move(node_fn)) { + BOTAN_ARG_CHECK(h < 32, "Invalid Merkle tree height"); + BOTAN_ARG_CHECK(n > 0, "Invalid Merkle tree node size"); + BOTAN_ARG_CHECK(leaf_batch > 0 && (leaf_batch & (leaf_batch - 1)) == 0, "Leaf batch must be a power of two"); +} + +/** + * Compute every node of the subtree of height @p height whose leftmost leaf is + * @p first_leaf, calling on_node(j, t, node) for each node + */ +template +void Merkle_Tree_Builder::walk(uint32_t first_leaf, uint32_t height, F on_node) const { + BOTAN_ASSERT_NOMSG(height <= m_h); + BOTAN_ASSERT_NOMSG(first_leaf % (uint32_t(1) << height) == 0 && first_leaf < (uint32_t(1) << m_h)); + + const size_t n = m_n; + const uint32_t leaf_count = uint32_t(1) << height; + // Both the batch size and the leaf count are powers of two, so batches are + // always full, and each batch is the bottom of a subtree + const uint32_t leaves_per_batch = std::min(leaf_count, m_leaf_batch); + const auto batch_height = static_cast(ctz(leaves_per_batch)); + std::vector layer(leaves_per_batch * n); + std::vector parents(leaves_per_batch / 2 * n); + // The left child at each height which is waiting for its right sibling + std::vector left_children(height * n); + // A node at height batch_height or above, preceded by its left sibling + std::vector pair(2 * n); + const auto right = std::span(pair).last(n); + + for(uint32_t b = 0; b != leaf_count; b += leaves_per_batch) { + m_leaf_fn(layer, first_leaf + b, leaves_per_batch); + + // The subtree above the batch, one layer at a time + uint32_t t = first_leaf + b; + for(uint32_t j = 0, count = leaves_per_batch; true; ++j) { + for(uint32_t i = 0; i != count; ++i) { + on_node(j, t + i, std::span(layer).subspan(i * n, n)); + } + if(count == 1) { + break; + } + count /= 2; + t /= 2; + const auto out = std::span(parents).first(count * n); + m_node_fn(out, j + 1, t, count, std::span(layer).first(2 * count * n)); + copy_mem(std::span(layer).first(count * n), std::span(out)); + } + + // Post-order traversal above the batches, combining each right child + // with its left sibling + copy_mem(right, std::span(layer).first(n)); + for(uint32_t j = batch_height; j != height; ++j) { + const auto left = std::span(left_children).subspan(j * n, n); + if(t % 2 == 0) { + copy_mem(left, std::span(right)); + break; + } + t /= 2; + copy_mem(std::span(pair).first(n), std::span(left)); + m_node_fn(std::span(layer).first(n), j + 1, t, 1, pair); + copy_mem(right, std::span(layer).first(n)); + on_node(j + 1, t, std::span(right)); + } + } +} + +std::vector Merkle_Tree_Builder::root() const { + std::vector root(m_n); + walk(0, m_h, [&](uint32_t j, uint32_t /*t*/, std::span node) { + if(j == m_h) { + copy_mem(std::span(root), node); + } + }); + + // The root is public, being part of the public key + CT::unpoison(root); + return root; +} + +std::pair Merkle_Tree_Builder::build(uint32_t q) const { + BOTAN_ARG_CHECK(q < (uint32_t(1) << m_h), "Invalid Merkle tree leaf index"); + + const uint32_t h = m_h; + const uint32_t k = Merkle_Treetop::subtree_height(h); + const size_t n = m_n; + const uint32_t s = q >> k; + + std::vector top((size_t(1) << (h - k + 1)) * n); + std::vector sub((size_t(1) << (k + 1)) * n); + + walk(0, h, [&](uint32_t j, uint32_t t, std::span node) { + if(j >= k) { + const size_t pos = (size_t(1) << (h - j)) + t; + copy_mem(std::span(top).subspan(pos * n, n), node); + } + if(j <= k && (t >> (k - j)) == s) { + const uint32_t layer_start = uint32_t(1) << (k - j); + const size_t pos = layer_start + (t & (layer_start - 1)); + copy_mem(std::span(sub).subspan(pos * n, n), node); + } + }); + + // The nodes are public, being part of signatures or the public key + CT::unpoison(top); + CT::unpoison(sub); + + return {Merkle_Treetop(h, n, std::move(top)), Merkle_Subtree(k, s, n, std::move(sub))}; +} + +std::optional Merkle_Tree_Builder::build_subtree(const Merkle_Treetop& treetop, uint32_t q) const { + BOTAN_ARG_CHECK(treetop.h() == m_h && treetop.n() == m_n, "Treetop does not belong to this tree"); + BOTAN_ARG_CHECK(q < (uint32_t(1) << m_h), "Invalid Merkle tree leaf index"); + + const uint32_t k = treetop.k(); + const size_t n = m_n; + const uint32_t s = q >> k; + + std::vector sub((size_t(1) << (k + 1)) * n); + + walk(s << k, k, [&](uint32_t j, uint32_t t, std::span node) { + const uint32_t layer_start = uint32_t(1) << (k - j); + const size_t pos = layer_start + (t & (layer_start - 1)); + copy_mem(std::span(sub).subspan(pos * n, n), node); + }); + + CT::unpoison(sub); + + Merkle_Subtree subtree(k, s, n, std::move(sub)); + if(!std::ranges::equal(subtree.node(k, s), treetop.node(k, s))) { + return std::nullopt; + } + return subtree; +} + +} // namespace Botan diff --git a/src/lib/utils/tree_hash/merkle_tree.h b/src/lib/utils/tree_hash/merkle_tree.h new file mode 100644 index 00000000000..94939c16237 --- /dev/null +++ b/src/lib/utils/tree_hash/merkle_tree.h @@ -0,0 +1,192 @@ +/* + * Merkle trees with a stored treetop + * (C) 2026 Jack Lloyd + * + * Botan is released under the Simplified BSD License (see license.txt) + */ + +#ifndef BOTAN_MERKLE_TREE_H_ +#define BOTAN_MERKLE_TREE_H_ + +#include +#include +#include +#include +#include +#include + +namespace Botan { + +/* + * Nodes of a Merkle tree are identified by their height j, the leaves having + * height 0, and their index t within that height, counting from the left. + */ + +/** + * Computes the leaves first_leaf, ..., first_leaf + count - 1 into out, + * which holds count nodes + */ +using Merkle_Leaf_Fn = std::function out, uint32_t first_leaf, uint32_t count)>; + +/** + * Computes the nodes at height j (at least 1) with indices first_t, ..., + * first_t + count - 1 into out, which holds count nodes. Their children are + * the 2 * count nodes in children, from left to right, which do not overlap out. + */ +using Merkle_Node_Fn = std::function out, uint32_t j, uint32_t first_t, uint32_t count, std::span children)>; + +class Merkle_Subtree; + +/** + * The top part of a Merkle tree of height h: every node at height k or above, + * where k = subtree_height(h). Together with the Merkle_Subtree containing a + * leaf, it provides the authentication path of that leaf. + */ +class BOTAN_TEST_API Merkle_Treetop final { + public: + /** + * Height of the subtrees below the treetop, chosen so that the lowest + * row of the treetop has at most 2^10 nodes + */ + static uint32_t subtree_height(uint32_t h); + + /** + * Size in bytes of the lowest row of the treetop of a tree of height + * @p h with nodes of @p n bytes + */ + static size_t row_size(uint32_t h, size_t n); + + /** + * Compute a treetop from its lowest row (see row()) + */ + static Merkle_Treetop from_row(uint32_t h, size_t n, std::span row, const Merkle_Node_Fn& node_fn); + + /** + * The nodes at height k from left to right + */ + std::span row() const; + + std::span root() const { return node(m_h, 0); } + + /** + * The node at height @p j (at least k) with index @p t + */ + std::span node(uint32_t j, uint32_t t) const; + + /** + * Write the authentication path of leaf @p q into @p out (h nodes): + * entry j is the sibling of the node at height j on the way from q to + * the root. + * + * @param subtree The subtree containing @p q. Unused, and may be null, + * if k is zero. + */ + void auth_path(std::span out, uint32_t q, const Merkle_Subtree* subtree) const; + + uint32_t h() const { return m_h; } + + uint32_t k() const { return m_k; } + + size_t n() const { return m_n; } + + private: + friend class Merkle_Tree_Builder; + + Merkle_Treetop(uint32_t h, size_t n, std::vector nodes); + + uint32_t m_h; + uint32_t m_k; + size_t m_n; + // Node (j, t) is at position 2^(h-j) + t, so the first entry is unused + std::vector m_nodes; +}; + +/** + * All nodes of one of the subtrees of height k hanging below a Merkle_Treetop + */ +class BOTAN_TEST_API Merkle_Subtree final { + public: + /** + * The subtree's position, counting from the left. Leaf q is in subtree + * number q >> k. + */ + uint32_t index() const { return m_index; } + + /** + * The node at height @p j (at most k) with index @p t, which must be + * within this subtree + */ + std::span node(uint32_t j, uint32_t t) const; + + private: + friend class Merkle_Tree_Builder; + + Merkle_Subtree(uint32_t k, uint32_t index, size_t n, std::vector nodes); + + uint32_t m_k; + uint32_t m_index; + size_t m_n; + // Node (j, t) is at position 2^(k-j) + t mod 2^(k-j), so the first entry is unused + std::vector m_nodes; +}; + +/** + * Computes the nodes of a Merkle tree of height h with nodes of n bytes + */ +class BOTAN_TEST_API Merkle_Tree_Builder final { + public: + /** + * @param h The height of the tree + * @param n The size of each node in bytes + * @param leaf_batch The number of leaves to request from @p leaf_fn at + * once, a power of two + * @param leaf_fn Computes the leaves + * @param node_fn Computes the interior nodes + */ + Merkle_Tree_Builder(uint32_t h, size_t n, uint32_t leaf_batch, Merkle_Leaf_Fn leaf_fn, Merkle_Node_Fn node_fn); + + /** + * Compute the root of the tree + */ + std::vector root() const; + + /** + * Compute the whole tree + * + * @return The treetop, and the subtree containing leaf @p q + */ + std::pair build(uint32_t q) const; + + /** + * Compute the subtree containing leaf @p q + * + * @return The subtree, or nullopt if its root does not match @p treetop + */ + std::optional build_subtree(const Merkle_Treetop& treetop, uint32_t q) const; + + /** + * Compute a treetop from its lowest row (see Merkle_Treetop::row()) + */ + Merkle_Treetop treetop_from_row(std::span row) const { + return Merkle_Treetop::from_row(m_h, m_n, row, m_node_fn); + } + + uint32_t h() const { return m_h; } + + size_t n() const { return m_n; } + + private: + template + void walk(uint32_t first_leaf, uint32_t height, F on_node) const; + + uint32_t m_h; + size_t m_n; + uint32_t m_leaf_batch; + Merkle_Leaf_Fn m_leaf_fn; + Merkle_Node_Fn m_node_fn; +}; + +} // namespace Botan + +#endif diff --git a/src/scripts/ci_build.py b/src/scripts/ci_build.py index 94d8b98199c..345e840a00d 100755 --- a/src/scripts/ci_build.py +++ b/src/scripts/ci_build.py @@ -934,12 +934,12 @@ def main(args=None): 'dsa_kat_verify', 'dsa_param', 'ecc_basemul', 'ecdsa_verify_wycheproof', 'ed25519_sign', 'elgamal_decrypt', 'elgamal_encrypt', 'elgamal_keygen', 'ffi_dh', 'ffi_dsa', 'ffi_elgamal', 'frodo_kat_tests', 'hash_nist_mc', - 'hss_lms_keygen', 'hss_lms_sign', 'mce_keygen', 'passhash9', 'pbkdf', + 'hss_lms_keygen', 'hss_lms_sign', 'hss_lms_subtrees', 'mce_keygen', 'passhash9', 'pbkdf', 'pk_concurrent_ops', 'pwdhash', 'rsa_encrypt', 'rsa_pss', 'rsa_pss_raw', 'scrypt', 'sphincsplus', 'sphincsplus_fors', 'slh_dsa_keygen', 'slh_dsa', 'srp6_kat', 'srp6_rt', 'unit_tls', 'x509_path_bsi', 'x509_path_rsa_pss', - 'xmss_keygen', 'xmss_keygen_reference', 'xmss_sign', 'xmss_unit_tests', - 'xmss_verify', 'xmss_verify_invalid', + 'xmss_encoding', 'xmss_keygen', 'xmss_keygen_reference', 'xmss_sign', 'xmss_subtrees', + 'xmss_unit_tests', 'xmss_verify', 'xmss_verify_invalid', ] slow_tests += [f"dilithium_kat_{mode}_{rand}" for mode in ('6x5', '8x7', '6x5_AES', '8x7_AES') for rand in ('Deterministic', 'Randomized')] slow_tests += [f"ml_dsa_kat_{mode}_{rand}" for mode in ('6x5', '8x7') for rand in ('Deterministic', 'Randomized')] diff --git a/src/scripts/test_cli.py b/src/scripts/test_cli.py index 3d70509816c..717f9da3b0b 100755 --- a/src/scripts/test_cli.py +++ b/src/scripts/test_cli.py @@ -817,7 +817,7 @@ def cli_xmss_sign_tests(tmp_dir): test_cli("hash", ["--no-fsname", msg], "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855") test_cli("keygen", ["--algo=XMSS", "--params=XMSS-SHA2_10_256", "--output=%s" % (priv_key)], "") - test_cli("hash", ["--no-fsname", priv_key], "737368AB8BFC6B0CDA0DF7FB6BD1DE48C2ABA81236F65E4E227920CECCC5F259") + test_cli("hash", ["--no-fsname", priv_key], "3DECE85CB919075130C81B299B5C9AC3B1F89E0F583E53A052DB3B93E33067F5") # If the updated key cannot be stored, no signature may be produced and # the key file must be left unchanged @@ -830,7 +830,7 @@ def cli_xmss_sign_tests(tmp_dir): try: test_cli("sign", [ro_key, msg], "", expected_stderr="Error: Error opening %s.tmp" % (ro_key), expected_rc=2) - test_cli("hash", ["--no-fsname", ro_key], "737368AB8BFC6B0CDA0DF7FB6BD1DE48C2ABA81236F65E4E227920CECCC5F259") + test_cli("hash", ["--no-fsname", ro_key], "3DECE85CB919075130C81B299B5C9AC3B1F89E0F583E53A052DB3B93E33067F5") finally: os.chmod(ro_dir, 0o700) @@ -842,7 +842,7 @@ def cli_xmss_sign_tests(tmp_dir): test_cli("sign", [priv_key, msg, "--output=%s" % (sig1)], "") test_cli("verify", [pub_key, msg, sig1], "Signature is valid") test_cli("hash", ["--no-fsname", sig1], "A37241040C0C7044DD502D92B69E8B931FF43FBC91CF4E3C869B23206EBFABF6") - test_cli("hash", ["--no-fsname", priv_key], "748E63766E8805A4CED94B7BC52F0A5EB2D6F8CECFD2CFC27C61DFA2C7DC1328") + test_cli("hash", ["--no-fsname", priv_key], "4CC07163F49C6D00853F7EB85A8B47DB978FD0ADCF7DD6475E55637011061C97") check_private_file(priv_key) if os.path.exists(priv_key + ".tmp"): logging.error("Temporary key file was left behind") @@ -850,7 +850,7 @@ def cli_xmss_sign_tests(tmp_dir): test_cli("sign", [priv_key, msg, "--output=%s" % (sig2)], "") test_cli("verify", [pub_key, msg, sig2], "Signature is valid") test_cli("hash", ["--no-fsname", sig2], "D593C1D0ADED11422248AE16CA77828CD2161CA3FCE3D0118A78D188C637D883") - test_cli("hash", ["--no-fsname", priv_key], "745903AC3BB7F55A6003BB59B13FC3BB48F4ACCAC7FE5888DD38031C55785B70") + test_cli("hash", ["--no-fsname", priv_key], "80FA8E0CC43FD9764E3C5C41636C7102D77C7F477FEC212F572074D9CB05FF13") # private key updates, public key is unchanged: test_cli("pkcs8", "--pub-out --output=%s %s" % (pub_key2, priv_key), "") @@ -860,15 +860,15 @@ def cli_xmss_sign_tests(tmp_dir): # verify that key is updated when creating a self-signed certificate test_cli("gen_self_signed", [priv_key, "Root", "--ca", "--path-limit=2", "--output="+root_crt], "") - test_cli("hash", ["--no-fsname", priv_key], "364744707707A05F9348848EF473CCCE600D337E9715EB5D899EE392E1B49FD7") + test_cli("hash", ["--no-fsname", priv_key], "35638708A46A2D1965311ADEFA5D23230B3867D635669668CC0707ADA5FC8B4F") # verify that key is updated after signing a certificate request test_cli("gen_pkcs10", "%s Intermediate --ca --output=%s" % (priv_key, int_csr)) - test_cli("hash", ["--no-fsname", priv_key], "C460DC6B4BAC18360C61F93F8E33762AECEDBC864E0D9EA7A2561A8B8CC04A89") + test_cli("hash", ["--no-fsname", priv_key], "0B1C863EBEB2E3AD2B8940F42AB7C84892FE3968941C692B6A5D4CA3A421E0B6") # verify that key is updated after issuing a certificate test_cli("sign_cert", "%s %s %s --output=%s" % (root_crt, priv_key, int_csr, int_crt)) - test_cli("hash", ["--no-fsname", priv_key], "DDFC14EADFC7EDCC569D038F6BCBBC359D035B1CBB7BB0814E134AA5BB8FB8C8") + test_cli("hash", ["--no-fsname", priv_key], "653F11616660F0C1268E3CC2926E5B7197E721F654D225BE489F32099E1DE0E5") test_cli("cert_verify", "%s %s" % (int_crt, root_crt), "Certificate passes validation checks") diff --git a/src/tests/test_hss_lms.cpp b/src/tests/test_hss_lms.cpp index 3a95d8ce67a..522b725f02f 100644 --- a/src/tests/test_hss_lms.cpp +++ b/src/tests/test_hss_lms.cpp @@ -11,16 +11,32 @@ #include "test_arb_eq.h" #include "test_pubkey.h" #include + #include #include #include #include #include + #include #include + #include + #include + #include #include #include #include #include #include + #include + + #if defined(BOTAN_TARGET_OS_HAS_THREADS) + #include + #endif + + #if defined(BOTAN_HAS_THREAD_UTILS) + #include + #include + #include + #endif #if defined(BOTAN_HAS_X509_CERTIFICATES) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) #include @@ -35,6 +51,13 @@ namespace Botan_Tests { namespace { +// Offset of the signature index in the private key encoding, after L +constexpr size_t sk_index_offset = sizeof(uint32_t); + +Botan::AlgorithmIdentifier hss_lms_sk_alg_id(std::string_view oid_name) { + return Botan::AlgorithmIdentifier(Botan::OID::from_string(oid_name), Botan::AlgorithmIdentifier::USE_EMPTY_PARAM); +} + /** * @brief Test the correct parsing of HSS-LMS parameters */ @@ -222,15 +245,17 @@ class HSS_LMS_Negative_Tests final : public Test { // HSS_LMS_PublicKey::key_length() auto sk = Botan::create_private_key("HSS-LMS", Test::rng(), "Truncated(SHA-256,192),HW(5,8)"); + // Raw bytes without an OID would accept the legacy format, which is a prefix + const auto alg_id = sk->pkcs8_algorithm_identifier(); auto sk_bytes = sk->private_key_bits(); result.test_no_throw("Entire private key valid", [&]() { - const Botan::HSS_LMS_PrivateKey key(sk_bytes); + const Botan::HSS_LMS_PrivateKey key(alg_id, sk_bytes); BOTAN_UNUSED(key); }); for(size_t n = 0; n < sk_bytes.size(); ++n) { result.test_throws("Partial private key invalid", [&]() { const std::span partial_key = {sk_bytes.data(), n}; - const Botan::HSS_LMS_PrivateKey key(partial_key); + const Botan::HSS_LMS_PrivateKey key(alg_id, partial_key); BOTAN_UNUSED(key); }); } @@ -273,8 +298,7 @@ class HSS_LMS_Statefulness_Test final : public Test { Botan::HSS_LMS_PrivateKey create_private_key_with_idx(uint64_t idx) { const auto sk = Botan::HSS_LMS_PrivateKey(Test::rng(), "Truncated(SHA-256,192),HW(5,8)"); auto bytes = sk.private_key_bits(); - // The index is store after the level (uint32_t) - Botan::store_be(idx, bytes.data() + sizeof(uint32_t)); + Botan::store_be(idx, bytes.data() + sk_index_offset); return Botan::HSS_LMS_PrivateKey(Botan::AlgorithmIdentifier(), bytes); } @@ -361,7 +385,7 @@ class HSS_LMS_Statefulness_Test final : public Test { const auto sk = Botan::HSS_LMS_PrivateKey(Test::rng(), "Truncated(SHA-256,192),HW(5,8),HW(25,8),HW(25,8),HW(25,8)"); auto bytes = sk.private_key_bits(); - Botan::store_be(std::numeric_limits::max(), bytes.data() + sizeof(uint32_t)); + Botan::store_be(std::numeric_limits::max(), bytes.data() + sk_index_offset); const auto exhausted_sk = Botan::HSS_LMS_PrivateKey(Botan::AlgorithmIdentifier(), bytes); result.test_opt_u64_eq("Exhausted key has no remaining signatures", exhausted_sk.remaining_operations(), 0); @@ -386,8 +410,9 @@ class HSS_LMS_Statefulness_Test final : public Test { // Patch the LMOTS algorithm type from SHA256_N24_W8 (0x08) to // SHA256_N24_W4 (0x07), pretending the same seed and identifier // belong to a key with a different Winternitz parameter - result.require("LMOTS type byte has expected value", bytes[19] == 0x08); - bytes[19] = 0x07; + const size_t lmots_type_lsb = sk_index_offset + sizeof(uint64_t) + 2 * sizeof(uint32_t) - 1; + result.require("LMOTS type byte has expected value", bytes[lmots_type_lsb] == 0x08); + bytes[lmots_type_lsb] = 0x07; // The index registry tracks the same key material under different // parameter sets independently. Nothing can prevent such (insecurely) @@ -579,6 +604,581 @@ class HSS_LMS_Missing_API_Test final : public Test { } }; +uint32_t u32_at(std::span bytes, size_t offset) { + if(offset + sizeof(uint32_t) > bytes.size()) { + throw Test_Error("HSS-LMS private key encoding is shorter than expected"); + } + return Botan::load_be(bytes.subspan(offset).first()); +} + +/** + * @brief Location of a section of an HSS-LMS private key in the current format + */ +struct HSS_LMS_SK_Section final { + size_t offset; // of the tag + uint32_t tag; + uint32_t length; +}; + +size_t section_body(const HSS_LMS_SK_Section& section) { + return section.offset + 2 * sizeof(uint32_t); +} + +// The nodes of an LMS tree section follow the level and tree number +size_t section_nodes(const HSS_LMS_SK_Section& section) { + return section_body(section) + sizeof(uint32_t) + sizeof(uint64_t); +} + +/** + * @brief Offsets within an HSS-LMS private key in the current format + */ +struct HSS_LMS_SK_Layout final { + size_t legacy_end; + size_t seed; + size_t root; + size_t section_count; + std::vector sections; +}; + +HSS_LMS_SK_Layout hss_lms_sk_layout(std::span bytes, const Botan::HSS_LMS_Params& params) { + const size_t L = params.L().get(); + const size_t m = params.params_at_level(Botan::HSS_Level(0)).lms_params().m(); + + HSS_LMS_SK_Layout layout{}; + layout.seed = sk_index_offset + sizeof(uint64_t) + L * 2 * sizeof(uint32_t); + layout.legacy_end = layout.seed + m + Botan::LMS_IDENTIFIER_LEN; + layout.root = layout.legacy_end; + layout.section_count = layout.root + m; + + size_t offset = layout.section_count + sizeof(uint32_t); + const uint32_t count = u32_at(bytes, layout.section_count); + for(uint32_t i = 0; i != count; ++i) { + const uint32_t tag = u32_at(bytes, offset); + const uint32_t length = u32_at(bytes, offset + sizeof(uint32_t)); + layout.sections.push_back({offset, tag, length}); + offset += 2 * sizeof(uint32_t) + length; + } + return layout; +} + +/** + * @brief The HSS index used for a signature, combined from the leaf used at each level + */ +uint64_t hss_signature_index(std::span sig, const Botan::HSS_LMS_Params& params) { + const auto parsed = Botan::HSS_Signature::from_bytes_or_throw(sig); + uint64_t idx = 0; + for(Botan::HSS_Level level(0); level < params.L(); ++level) { + const auto& lms_sig = (level + 1 < params.L()) ? parsed.signed_pub_key(level).signature() : parsed.bottom_sig(); + idx = (idx << params.params_at_level(level).lms_params().h()) | lms_sig.q().get(); + } + return idx; +} + +/** + * @brief Tests of the private key encoding, and the tree data cached in the key. + */ +class HSS_LMS_Encoding_Test_Base : public Test { + protected: + static constexpr std::string_view TwoLevelParams = "Truncated(SHA-256,192),HW(5,1),HW(5,1)"; + + std::vector message() const { return {0xde, 0xad, 0xbe, 0xef}; } + + std::vector sign(const Botan::Private_Key& sk) const { + Botan::PK_Signer signer(sk, Test::rng(), ""); + return signer.sign_message(message(), Test::rng()); + } + + bool verify(const Botan::Public_Key& pk, std::span sig) const { + Botan::PK_Verifier verifier(pk, ""); + return verifier.verify_message(message(), sig); + } + + static Botan::HSS_LMS_PrivateKey load(std::span bytes) { + return Botan::HSS_LMS_PrivateKey(hss_lms_sk_alg_id("HSS-LMS-Private-Key"), bytes); + } + + static Botan::HSS_LMS_PrivateKey load_legacy(std::span bytes) { + return Botan::HSS_LMS_PrivateKey(hss_lms_sk_alg_id("HSS-LMS-Private-Key-legacy"), bytes); + } + + static std::vector legacy_encoding(std::span bytes, const Botan::HSS_LMS_Params& params) { + const auto layout = hss_lms_sk_layout(bytes, params); + return std::vector(bytes.begin(), bytes.begin() + layout.legacy_end); + } + + Test::Result test_current_encoding() { + Test::Result result("HSS-LMS private key encoding"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + const size_t m = params.params_at_level(Botan::HSS_Level(0)).lms_params().m(); + + result.test_str_eq( + "private key OID", sk.pkcs8_algorithm_identifier().oid().to_string(), "1.3.6.1.4.1.25258.1.19"); + + const auto fresh = sk.private_key_bits(); + const auto fresh_layout = hss_lms_sk_layout(fresh, params); + result.test_sz_eq("only the top tree is cached before signing", fresh_layout.sections.size(), 1); + + sign(sk); + + const auto bytes = sk.private_key_bits(); + const auto layout = hss_lms_sk_layout(bytes, params); + result.test_sz_eq("both trees are cached after signing", layout.sections.size(), 2); + result.test_sz_eq("encoding has no trailing data", + section_body(layout.sections.back()) + layout.sections.back().length, + bytes.size()); + + const auto pk_bits = sk.public_key_bits(); + result.test_bin_eq( + "encoding contains the root", std::span(bytes).subspan(layout.root, m), std::span(pk_bits).last(m)); + + const auto loaded = load(bytes); + result.test_bin_eq("loaded key has the same public key", loaded.public_key_bits(), pk_bits); + result.test_bin_eq("encoding round trips", loaded.private_key_bits(), bytes); + + const auto sig = sign(loaded); + result.test_u64_eq("loaded key continues at the next index", hss_signature_index(sig, params), 1); + result.test_is_true("signature of loaded key is valid", verify(sk, sig)); + + return result; + } + + Test::Result test_legacy_encoding() { + Test::Result result("HSS-LMS legacy private key encoding"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + sign(sk); + + const auto legacy = legacy_encoding(sk.private_key_bits(), params); + + const auto loaded = load_legacy(legacy); + result.test_bin_eq("legacy key has the same public key", loaded.public_key_bits(), sk.public_key_bits()); + + const auto sig = sign(loaded); + result.test_u64_eq("legacy key continues at the next index", hss_signature_index(sig, params), 1); + result.test_is_true("signature of legacy key is valid", verify(sk, sig)); + + const auto reencoded = loaded.private_key_bits(); + result.test_sz_eq( + "re-encoded legacy key caches both trees", hss_lms_sk_layout(reencoded, params).sections.size(), 2); + result.test_bin_eq("re-encoded legacy key starts with the legacy fields", + std::span(reencoded).first(legacy.size()), + legacy_encoding(sk.private_key_bits(), params)); + + // A PKCS #8 structure as written by older versions + const auto pkcs8 = Botan::DER_Encoder() + .start_sequence() + .encode(size_t(0)) + .encode(hss_lms_sk_alg_id("HSS-LMS-Private-Key-legacy")) + .encode(legacy, Botan::ASN1_Type::OctetString) + .end_cons() + .get_contents_unlocked(); + const auto from_pkcs8 = Botan::PKCS8::load_key(pkcs8); + result.test_bin_eq( + "legacy PKCS #8 key has the same public key", from_pkcs8->public_key_bits(), sk.public_key_bits()); + result.test_is_true("signature of legacy PKCS #8 key is valid", verify(sk, sign(*from_pkcs8))); + + return result; + } + + Test::Result test_algorithm_identifiers() { + Test::Result result("HSS-LMS private key algorithm identifiers"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + const auto current = sk.private_key_bits(); + const auto legacy = legacy_encoding(current, params); + + const auto from_pkcs8 = Botan::PKCS8::load_key(sk.private_key_info()); + result.test_bin_eq("PKCS #8 round trip", from_pkcs8->private_key_bits(), current); + + result.test_no_throw("raw bytes in the current format", [&] { + const Botan::HSS_LMS_PrivateKey key(Botan::AlgorithmIdentifier(), current); + result.test_bin_eq("same public key", key.public_key_bits(), sk.public_key_bits()); + }); + result.test_no_throw("raw bytes in the legacy format", [&] { + const Botan::HSS_LMS_PrivateKey key(Botan::AlgorithmIdentifier(), legacy); + result.test_bin_eq("same public key", key.public_key_bits(), sk.public_key_bits()); + }); + + result.test_throws("legacy OID with the current format", [&] { load_legacy(current); }); + result.test_throws("current OID with the legacy format", [&] { load(legacy); }); + result.test_throws( + "public key OID", [&] { Botan::HSS_LMS_PrivateKey(sk.algorithm_identifier(), current); }); + + return result; + } + + Test::Result test_root_is_taken_from_encoding() { + Test::Result result("HSS-LMS root is not recomputed on load"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + + auto bytes = sk.private_key_bits(); + const auto layout = hss_lms_sk_layout(bytes, params); + bytes.at(layout.seed) ^= 0x01; + + const auto corrupted = load(bytes); + result.test_bin_eq( + "public key is taken from the stored root", corrupted.public_key_bits(), sk.public_key_bits()); + + result.test_is_true("strong key check of a valid key passes", sk.check_key(Test::rng(), true)); + result.test_is_true("weak key check does not compute the tree", corrupted.check_key(Test::rng(), false)); + result.test_is_true("strong key check detects a seed not matching the root", + !corrupted.check_key(Test::rng(), true)); + + result.test_throws("a signature not matching the root is not released", + [&] { sign(corrupted); }); + result.test_throws("a seed not matching the root is detected once recomputed", + [&] { sign(corrupted); }); + + return result; + } + + Test::Result test_corrupt_cache_is_discarded() { + Test::Result result("HSS-LMS corrupted cache data"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + sign(sk); + + const auto bytes = sk.private_key_bits(); + const auto layout = hss_lms_sk_layout(bytes, params); + result.require("both trees are cached", layout.sections.size() == 2); + + const auto& top = layout.sections[0]; + const auto& bottom = layout.sections[1]; + const auto& bottom_lms_params = params.params_at_level(Botan::HSS_Level(1)).lms_params(); + const size_t bottom_row_size = Botan::Merkle_Treetop::row_size(bottom_lms_params.h(), bottom_lms_params.m()); + + const auto signs_validly_after_flipping = [&](std::string_view what, size_t offset) { + auto corrupted = bytes; + corrupted.at(offset) ^= 0x01; + const auto loaded = load(corrupted); + const auto sig = sign(loaded); + result.test_is_true(Botan::fmt("{}: signature is valid", what), verify(sk, sig)); + }; + + signs_validly_after_flipping("top tree nodes", section_nodes(top)); + signs_validly_after_flipping("bottom tree number", section_nodes(bottom) - 1); + signs_validly_after_flipping("bottom tree nodes", section_nodes(bottom) + bottom_row_size - 1); + signs_validly_after_flipping("signature over bottom tree", section_nodes(bottom) + bottom_row_size + 40); + signs_validly_after_flipping("bottom tree public key", section_body(bottom) + bottom.length - 1); + + auto corrupted_root = bytes; + corrupted_root.at(layout.root) ^= 0x01; + const auto loaded = load(corrupted_root); + result.test_throws("signing with a corrupted root fails", [&] { sign(loaded); }); + + return result; + } + + Test::Result test_stale_cache_is_discarded() { + Test::Result result("HSS-LMS stale cache data"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + sign(sk); + + // Skip ahead to the second bottom tree, which makes the cached one stale + auto bytes = sk.private_key_bits(); + Botan::store_be(uint64_t(32), bytes.data() + sk_index_offset); + + const auto loaded = load(bytes); + const auto sig = sign(loaded); + result.test_u64_eq("signature uses the patched index", hss_signature_index(sig, params), 32); + result.test_is_true("signature is valid", verify(sk, sig)); + + const auto reencoded = loaded.private_key_bits(); + const auto layout = hss_lms_sk_layout(reencoded, params); + result.require("both trees are cached", layout.sections.size() == 2); + result.test_u64_eq( + "the new bottom tree is cached", + Botan::load_be( + std::span(reencoded).subspan(section_body(layout.sections[1]) + sizeof(uint32_t)).first<8>()), + 1); + + return result; + } + + Test::Result test_unknown_sections_are_ignored() { + Test::Result result("HSS-LMS unknown private key sections"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + + auto bytes = sk.private_key_bits(); + const auto layout = hss_lms_sk_layout(bytes, params); + Botan::store_be(u32_at(bytes, layout.section_count) + 1, bytes.data() + layout.section_count); + const auto unknown = Botan::concat>( + Botan::store_be(uint32_t(0x7fffffff)), Botan::store_be(uint32_t(3)), std::array{1, 2, 3}); + bytes.insert(bytes.end(), unknown.begin(), unknown.end()); + + const auto loaded = load(bytes); + result.test_is_true("key with an unknown section signs validly", verify(sk, sign(loaded))); + + return result; + } + + Test::Result test_malformed_encodings_are_rejected() { + Test::Result result("HSS-LMS malformed private key encodings"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + sign(sk); + + const auto bytes = sk.private_key_bits(); + const auto layout = hss_lms_sk_layout(bytes, params); + result.require("both trees are cached", layout.sections.size() == 2); + + const auto rejects = [&](std::string_view what, const auto& patch) { + auto patched = bytes; + patch(patched); + result.test_throws(what, [&] { load(patched); }); + }; + + rejects("trailing data", [](auto& b) { b.push_back(0); }); + rejects("missing section", [&](auto& b) { Botan::store_be(uint32_t(3), b.data() + layout.section_count); }); + rejects("wrong tree section length", [&](auto& b) { + Botan::store_be(layout.sections[0].length - 1, b.data() + layout.sections[0].offset + sizeof(uint32_t)); + }); + rejects("tree sections out of order", + [&](auto& b) { Botan::store_be(uint32_t(0), b.data() + section_body(layout.sections[1])); }); + rejects("tree section for a level that does not exist", + [&](auto& b) { Botan::store_be(uint32_t(2), b.data() + section_body(layout.sections[1])); }); + + return result; + } + + Test::Result test_subtrees() { + Test::Result result("HSS-LMS trees with subtrees"); + + // Trees higher than 10 store their nodes down to height h - 10 and + // recompute the subtrees below as needed + const std::string_view hss_params_str = "Truncated(SHA-256,192),HW(15,1)"; + const Botan::HSS_LMS_Params params(hss_params_str); + const auto& lms_params = params.params_at_level(Botan::HSS_Level(0)).lms_params(); + const auto& lmots_params = params.params_at_level(Botan::HSS_Level(0)).lmots_params(); + result.test_u32_eq("subtree height", Botan::Merkle_Treetop::subtree_height(lms_params.h()), 5); + + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), hss_params_str); + const auto layout = hss_lms_sk_layout(sk.private_key_bits(), params); + result.require("top tree is cached", layout.sections.size() == 1); + result.test_sz_eq("cached top tree has 2^10 nodes", + layout.sections[0].length, + sizeof(uint32_t) + sizeof(uint64_t) + 1024 * lms_params.m()); + + // Index 33 is in the second subtree + for(uint64_t i = 0; i != 33; ++i) { + sign(sk); + } + const auto loaded = load(sk.private_key_bits()); + const auto sig = sign(loaded); + result.test_u64_eq("signature index", hss_signature_index(sig, params), 33); + result.test_is_true("signature using a recomputed subtree is valid", verify(sk, sig)); + + // The same on the level of a single LMS tree + const Botan::LMS_Identifier identifier( + Test::rng().random_vec>(Botan::LMS_IDENTIFIER_LEN)); + const Botan::LMS_PrivateKey lms_sk( + lms_params, lmots_params, identifier, Test::rng().random_vec(lms_params.m())); + const Botan::LMS_PrivateKey other_lms_sk( + lms_params, lmots_params, identifier, Test::rng().random_vec(lms_params.m())); + + const Botan::LMS_Tree_Node_Idx q(40); + const auto [treetop, subtree] = lms_sk.build_tree(q); + result.test_u32_eq("leaf 40 is in subtree 1", subtree.index(), 1); + result.test_bin_eq("subtree root is part of the treetop", subtree.node(5, 1), treetop.node(5, 1)); + result.test_bin_eq("treetop from its row", + Botan::lms_treetop_from_row(lms_params, identifier, treetop.row()).root(), + treetop.root()); + + const auto rebuilt = lms_sk.build_subtree(treetop, q); + result.test_is_true("subtree is recomputed", rebuilt.has_value()); + if(rebuilt.has_value()) { + result.test_bin_eq("recomputed subtree matches", rebuilt->node(4, 2), subtree.node(4, 2)); + } + result.test_is_true("subtree of another key does not match the treetop", + !other_lms_sk.build_subtree(treetop, q).has_value()); + + Botan::LMS_Signature_Bytes lms_sig(Botan::LMS_Signature::size(lms_params, lmots_params)); + const Botan::LMS_Message msg(message()); + lms_sk.sign_with_nodes(lms_sig, q, msg, treetop, &subtree); + const Botan::LMS_PublicKey lms_pk(lms_params, lmots_params, identifier, Botan::LMS_Tree_Node(treetop.root())); + Botan::BufferSlicer slicer(lms_sig); + result.test_is_true("LMS signature using stored nodes is valid", + lms_pk.verify_signature(msg, Botan::LMS_Signature::from_bytes_or_throw(slicer))); + + return result; + } + + #if defined(BOTAN_TARGET_OS_HAS_THREADS) + Test::Result test_concurrent_signing() { + Test::Result result("HSS-LMS concurrent signing with separately loaded keys"); + + const Botan::HSS_LMS_Params params(TwoLevelParams); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), TwoLevelParams); + + const auto bytes = sk.private_key_bits(); + const auto legacy = legacy_encoding(bytes, params); + + // More threads than key objects, so some objects are shared between + // threads. Half of the objects are loaded from the legacy encoding. + constexpr size_t key_objects = 4; + constexpr size_t threads = 8; + // The bottom trees have 32 leaves, so this crosses several of them + constexpr size_t sigs_per_thread = 20; + constexpr size_t total_sigs = threads * sigs_per_thread; + + std::vector> keys; + for(size_t i = 0; i != key_objects; ++i) { + keys.push_back( + std::make_unique((i % 2 == 0) ? load(bytes) : load_legacy(legacy))); + } + + const auto thread_message = [](size_t t, size_t i) { + return std::vector{static_cast(t), static_cast(i)}; + }; + + std::vector>>> futures; + futures.reserve(threads); + for(size_t t = 0; t != threads; ++t) { + futures.push_back(std::async(std::launch::async, [&, t]() { + auto thread_rng = Test::new_rng(Botan::fmt("{} thread {}", result.who(), t)); + Botan::PK_Signer signer(*keys[t % key_objects], *thread_rng, ""); + std::vector> sigs; + for(size_t i = 0; i != sigs_per_thread; ++i) { + sigs.push_back(signer.sign_message(thread_message(t, i), *thread_rng)); + } + return sigs; + })); + } + + Botan::PK_Verifier verifier(sk, ""); + std::set indices; + for(size_t t = 0; t != threads; ++t) { + try { + const auto sigs = futures[t].get(); + for(size_t i = 0; i != sigs.size(); ++i) { + if(!verifier.verify_message(thread_message(t, i), sigs[i])) { + result.test_failure(Botan::fmt("signature {} of thread {} is invalid", i, t)); + } + if(!indices.insert(hss_signature_index(sigs[i], params)).second) { + result.test_failure(Botan::fmt("signature {} of thread {} reuses an index", i, t)); + } + } + } catch(const std::exception& e) { + result.test_failure(Botan::fmt("thread {} failed", t), e.what()); + } + } + + result.test_sz_eq("each signature used its own index", indices.size(), total_sigs); + result.test_is_true("indices are consecutive", !indices.empty() && *indices.rbegin() == total_sigs - 1); + result.test_opt_u64_eq("all copies share the state", keys[1]->remaining_operations(), 1024 - total_sigs); + + const auto reloaded = load(keys[1]->private_key_bits()); + const auto sig = sign(reloaded); + result.test_u64_eq("reloaded key continues after all threads", hss_signature_index(sig, params), total_sigs); + result.test_is_true("signature of reloaded key is valid", verify(sk, sig)); + + return result; + } + #endif + + #if defined(BOTAN_HAS_THREAD_UTILS) + /** + * Computing a tree uses the thread pool, whose threads may themselves be + * signing with the same key. That is the case if the application provides + * a Work_Executor running on its own threads. Those threads must not wait + * for a tree being computed elsewhere, which in turn waits for them. + */ + Test::Result test_signing_within_pool_work() { + Test::Result result("HSS-LMS signing within thread pool work"); + + // The first signature computes the bottom tree + const std::string_view hss_params_str = "SHA-256,HW(5,1),HW(5,4)"; + const Botan::HSS_LMS_Params params(hss_params_str); + const Botan::HSS_LMS_PrivateKey sk(Test::rng(), hss_params_str); + + const auto sign_as = [&](size_t t) { + auto thread_rng = Test::new_rng(Botan::fmt("{} thread {}", result.who(), t)); + Botan::PK_Signer signer(sk, *thread_rng, ""); + return signer.sign_message(std::vector{static_cast(t)}, *thread_rng); + }; + + auto& pool = Botan::Thread_Pool::global_instance(); + const size_t workers = pool.worker_count(); + const auto remaining = sk.remaining_operations(); + + auto outside = std::async(std::launch::async, sign_as, workers); + + // Once it has reserved its index, that thread is computing the tree + while(sk.remaining_operations() == remaining && + outside.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { + std::this_thread::yield(); + } + + std::vector>> in_pool; + in_pool.reserve(workers); + for(size_t t = 0; t != workers; ++t) { + in_pool.push_back(pool.run(sign_as, t)); + } + + Botan::PK_Verifier verifier(sk, ""); + std::set indices; + for(size_t t = 0; t != workers + 1; ++t) { + try { + const auto sig = (t == workers) ? outside.get() : in_pool[t].get(); + result.test_is_true("signature is valid", + verifier.verify_message(std::vector{static_cast(t)}, sig)); + indices.insert(hss_signature_index(sig, params)); + } catch(const std::exception& e) { + result.test_failure(Botan::fmt("thread {} failed", t), e.what()); + } + } + + result.test_sz_eq("each signature used its own index", indices.size(), workers + 1); + + return result; + } + #endif +}; + +class HSS_LMS_Encoding_Test final : public HSS_LMS_Encoding_Test_Base { + public: + std::vector run() final { + std::vector results = {test_current_encoding(), + test_legacy_encoding(), + test_algorithm_identifiers(), + test_root_is_taken_from_encoding(), + test_corrupt_cache_is_discarded(), + test_stale_cache_is_discarded(), + test_unknown_sections_are_ignored(), + test_malformed_encodings_are_rejected()}; + + #if defined(BOTAN_TARGET_OS_HAS_THREADS) + results.push_back(test_concurrent_signing()); + #endif + + #if defined(BOTAN_HAS_THREAD_UTILS) + results.push_back(test_signing_within_pool_work()); + #endif + + return results; + } +}; + +/** + * @brief Separate from HSS_LMS_Encoding_Test, since computing trees of height 15 is slow under valgrind. + */ +class HSS_LMS_Subtree_Test final : public HSS_LMS_Encoding_Test_Base { + public: + std::vector run() final { return {test_subtrees()}; } +}; + #if defined(BOTAN_HAS_X509_CERTIFICATES) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) /** * @brief Test with the example certificate from RFC 9802 Appendix A. @@ -604,6 +1204,8 @@ BOTAN_REGISTER_TEST("pubkey", "hss_lms_keygen", HSS_LMS_Key_Generation_Test); BOTAN_REGISTER_TEST("pubkey", "hss_lms_negative", HSS_LMS_Negative_Tests); BOTAN_REGISTER_TEST("pubkey", "hss_lms_state", HSS_LMS_Statefulness_Test); BOTAN_REGISTER_TEST("pubkey", "hss_lms_api", HSS_LMS_Missing_API_Test); +BOTAN_REGISTER_TEST("pubkey", "hss_lms_encoding", HSS_LMS_Encoding_Test); +BOTAN_REGISTER_TEST("pubkey", "hss_lms_subtrees", HSS_LMS_Subtree_Test); #if defined(BOTAN_HAS_X509_CERTIFICATES) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) BOTAN_REGISTER_TEST("pubkey", "hss_lms_x509", HSS_LMS_X509_Test); diff --git a/src/tests/test_utils_merkle_tree.cpp b/src/tests/test_utils_merkle_tree.cpp new file mode 100644 index 00000000000..4d29065d50d --- /dev/null +++ b/src/tests/test_utils_merkle_tree.cpp @@ -0,0 +1,275 @@ +/* +* (C) 2026 Jack Lloyd +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include "tests.h" + +// The Merkle tree helper is an internal module pulled in by these +#if defined(BOTAN_HAS_SHA2_32) && (defined(BOTAN_HAS_HSS_LMS) || defined(BOTAN_HAS_XMSS_RFC8391)) + #include + #include + #include + #include + #include + #include + #include + #include + #include +#endif + +namespace Botan_Tests { + +namespace { + +#if defined(BOTAN_HAS_SHA2_32) && (defined(BOTAN_HAS_HSS_LMS) || defined(BOTAN_HAS_XMSS_RFC8391)) + +class Merkle_Tree_Test final : public Test { + public: + std::vector run() override { + return {test_tree(13, 8), + test_tree(10, 32), + test_tree(4, 32), + test_tree(0, 1), + test_mismatching_data(), + test_argument_checks()}; + } + + private: + static constexpr size_t N = 32; + + using Reference_Tree = std::vector>>; + + /** + * Leaves depend on @p seed, so that different trees can be built + */ + static Botan::Merkle_Leaf_Fn leaf_fn(uint8_t seed, std::vector* batches = nullptr) { + return [seed, + batches, + hash = std::shared_ptr(Botan::HashFunction::create_or_throw("SHA-256"))]( + std::span out, uint32_t first_leaf, uint32_t count) { + if(batches != nullptr) { + batches->push_back(count); + } + for(uint32_t i = 0; i != count; ++i) { + hash->update(seed); + hash->update_be(first_leaf + i); + hash->final(out.subspan(i * N, N)); + } + }; + } + + /** + * Records the height and count of each batch of nodes in @p batches + */ + static Botan::Merkle_Node_Fn node_fn(std::vector>* batches = nullptr) { + return [batches, hash = std::shared_ptr(Botan::HashFunction::create_or_throw("SHA-256"))]( + std::span out, + uint32_t j, + uint32_t first_t, + uint32_t count, + std::span children) { + if(batches != nullptr) { + batches->emplace_back(j, count); + } + for(uint32_t i = 0; i != count; ++i) { + hash->update_be(j); + hash->update_be(first_t + i); + hash->update(children.subspan(2 * i * N, 2 * N)); + hash->final(out.subspan(i * N, N)); + } + }; + } + + /** + * All nodes, indexed by height and index, computed from the definition + */ + static Reference_Tree reference_tree(uint32_t h, uint8_t seed) { + const size_t leaves = size_t(1) << h; + std::vector leaf_bytes(leaves * N); + leaf_fn(seed)(leaf_bytes, 0, static_cast(leaves)); + + Reference_Tree nodes(h + 1); + for(size_t t = 0; t != leaves; ++t) { + nodes[0].emplace_back(leaf_bytes.begin() + t * N, leaf_bytes.begin() + (t + 1) * N); + } + + const auto node = node_fn(); + for(uint32_t j = 1; j <= h; ++j) { + for(uint32_t t = 0; t != (uint32_t(1) << (h - j)); ++t) { + std::vector children = nodes[j - 1][2 * t]; + children.insert(children.end(), nodes[j - 1][2 * t + 1].begin(), nodes[j - 1][2 * t + 1].end()); + std::vector out(N); + node(out, j, t, 1, children); + nodes[j].push_back(out); + } + } + return nodes; + } + + static void check_auth_path(Test::Result& result, + const Reference_Tree& ref, + uint32_t q, + const Botan::Merkle_Treetop& treetop, + const Botan::Merkle_Subtree* subtree) { + std::vector path(treetop.h() * N); + treetop.auth_path(path, q, subtree); + for(uint32_t j = 0; j != treetop.h(); ++j) { + result.test_bin_eq( + Botan::fmt("leaf {} auth path entry {}", q, j), std::span(path).subspan(j * N, N), ref[j][(q >> j) ^ 1]); + } + } + + static void check_subtree(Test::Result& result, + const Reference_Tree& ref, + uint32_t k, + const Botan::Merkle_Subtree& subtree) { + const uint32_t s = subtree.index(); + for(uint32_t j = 0; j <= k; ++j) { + for(uint32_t t = s << (k - j); t != (s + 1) << (k - j); ++t) { + result.test_bin_eq(Botan::fmt("subtree {} node ({}, {})", s, j, t), subtree.node(j, t), ref[j][t]); + } + } + } + + static Test::Result test_tree(uint32_t h, uint32_t leaf_batch) { + Test::Result result(Botan::fmt("Merkle tree of height {}", h)); + + const auto ref = reference_tree(h, 1); + std::vector batches; + std::vector> node_batches; + const Botan::Merkle_Tree_Builder tree(h, N, leaf_batch, leaf_fn(1, &batches), node_fn(&node_batches)); + const uint32_t k = Botan::Merkle_Treetop::subtree_height(h); + const uint32_t leaves = uint32_t(1) << h; + + result.test_bin_eq("root", tree.root(), ref[h][0]); + const uint32_t expected_batch = std::min(leaves, leaf_batch); + result.test_sz_eq("number of leaf batches", batches.size(), leaves / expected_batch); + result.test_is_true("leaves are computed in full batches", + std::ranges::all_of(batches, [&](uint32_t b) { return b == expected_batch; })); + + // One call per layer above each leaf batch, then one per node above the batches + const uint32_t leaf_batches = leaves / expected_batch; + const auto batch_height = static_cast(std::countr_zero(expected_batch)); + result.test_sz_eq( + "number of node batches", node_batches.size(), leaf_batches * batch_height + leaf_batches - 1); + size_t nodes_computed = 0; + for(const auto& batch : node_batches) { + nodes_computed += batch.second; + } + result.test_sz_eq("every interior node is computed once", nodes_computed, leaves - 1); + + std::set qs = {0, leaves / 3, leaves - 1}; + if(leaves > 1) { + qs.insert(1); + } + for(const uint32_t q : qs) { + const auto [treetop, subtree] = tree.build(q); + result.test_u32_eq("treetop height", treetop.h(), h); + result.test_u32_eq("subtree height", treetop.k(), k); + result.test_bin_eq("treetop root", treetop.root(), ref[h][0]); + result.test_u32_eq("subtree index", subtree.index(), q >> k); + + std::vector row; + for(const auto& node : ref[k]) { + row.insert(row.end(), node.begin(), node.end()); + } + result.test_bin_eq("treetop row", treetop.row(), row); + result.test_sz_eq("row size", row.size(), Botan::Merkle_Treetop::row_size(h, N)); + + node_batches.clear(); + const auto from_row = tree.treetop_from_row(row); + result.test_sz_eq("treetop is computed one layer at a time", node_batches.size(), h - k); + for(const auto& [j, count] : node_batches) { + result.test_u32_eq("treetop layer size", count, uint32_t(1) << (h - j)); + } + for(uint32_t j = k; j <= h; ++j) { + for(uint32_t t = 0; t != (uint32_t(1) << (h - j)); ++t) { + if(!std::ranges::equal(from_row.node(j, t), ref[j][t])) { + result.test_failure(Botan::fmt("treetop from row node ({}, {})", j, t)); + } + } + } + + check_subtree(result, ref, k, subtree); + check_auth_path(result, ref, q, treetop, &subtree); + + const auto rebuilt = tree.build_subtree(treetop, q); + result.require("subtree is rebuilt", rebuilt.has_value()); + check_subtree(result, ref, k, rebuilt.value()); + + // Signing with another leaf, which may be in another subtree + const uint32_t other = (q + leaves / 2 + 1) % leaves; + const auto other_subtree = tree.build_subtree(from_row, other); + result.require("other subtree is built", other_subtree.has_value()); + result.test_u32_eq("other subtree index", other_subtree->index(), other >> k); + check_auth_path(result, ref, other, from_row, &other_subtree.value()); + + if(k == 0) { + check_auth_path(result, ref, other, from_row, nullptr); + } + } + + return result; + } + + static Test::Result test_mismatching_data() { + Test::Result result("Merkle tree with mismatching data"); + + const uint32_t h = 12; + const Botan::Merkle_Tree_Builder tree(h, N, 16, leaf_fn(1), node_fn()); + const Botan::Merkle_Tree_Builder other_tree(h, N, 16, leaf_fn(2), node_fn()); + + const auto [treetop, subtree] = tree.build(5); + result.test_is_true("subtree of another tree does not match", + !other_tree.build_subtree(treetop, 5).has_value()); + result.test_is_true("subtree of the same tree matches", tree.build_subtree(treetop, 100).has_value()); + + std::vector row(treetop.row().begin(), treetop.row().end()); + row.at(row.size() - 1) ^= 0x01; + const auto corrupted = tree.treetop_from_row(row); + result.test_is_true("corrupted row changes the root", !std::ranges::equal(corrupted.root(), treetop.root())); + result.test_is_true("subtree does not match a corrupted treetop", + !tree.build_subtree(corrupted, (uint32_t(1) << h) - 1).has_value()); + + return result; + } + + static Test::Result test_argument_checks() { + Test::Result result("Merkle tree argument checks"); + + result.test_throws( + "height 32", [] { const Botan::Merkle_Tree_Builder tree(32, N, 16, leaf_fn(1), node_fn()); }); + result.test_throws("leaf batch not a power of two", [] { + const Botan::Merkle_Tree_Builder tree(5, N, 3, leaf_fn(1), node_fn()); + }); + + const uint32_t h = 12; + const Botan::Merkle_Tree_Builder tree(h, N, 16, leaf_fn(1), node_fn()); + // Not a structured binding, since clang 14 cannot capture those in a lambda + const auto built = tree.build(0); + const auto& treetop = built.first; + const auto& subtree = built.second; + std::vector path(h * N); + + result.test_throws("leaf out of range", [&] { tree.build(uint32_t(1) << h); }); + result.test_throws( + "row of the wrong size", [&] { tree.treetop_from_row(std::vector(treetop.row().size() - 1)); }); + result.test_throws("missing subtree", [&] { treetop.auth_path(path, 0, nullptr); }); + result.test_throws("subtree not containing the leaf", + [&] { treetop.auth_path(path, 4, &subtree); }); + result.test_throws("wrong path size", + [&] { treetop.auth_path(std::span(path).first(N), 0, &subtree); }); + + return result; + } +}; + +BOTAN_REGISTER_TEST("utils", "merkle_tree", Merkle_Tree_Test); + +#endif + +} // namespace + +} // namespace Botan_Tests diff --git a/src/tests/test_xmss.cpp b/src/tests/test_xmss.cpp index 9507aa07a17..5a58e2e6d09 100644 --- a/src/tests/test_xmss.cpp +++ b/src/tests/test_xmss.cpp @@ -13,14 +13,31 @@ #include "test_pubkey.h" #include "test_rng.h" #include + #include #include #include #include + #include #include #include #include + #include + #include #include + #include #include + #include + #include + + #if defined(BOTAN_TARGET_OS_HAS_THREADS) + #include + #endif + + #if defined(BOTAN_HAS_THREAD_UTILS) + #include + #include + #include + #endif #if defined(BOTAN_TARGET_OS_HAS_POSIX1) #include @@ -146,7 +163,10 @@ class XMSS_Keygen_Reference_Test final : public Text_Based_Test { const auto xmss_algo = Botan::XMSS_Parameters::xmss_id_from_string(vars.get_req_str("Params")); const Botan::XMSS_PrivateKey keypair(xmss_algo, fixed_rng); - result.test_bin_eq("Generated private key matches", keypair.raw_private_key(), vars.get_req_bin("PrivateKey")); + // The encoding continues with the tree data cached by Botan + const auto expected_sk = vars.get_req_bin("PrivateKey"); + const auto sk = keypair.raw_private_key(); + result.test_bin_eq("Generated private key matches", std::span(sk).first(expected_sk.size()), expected_sk); result.test_bin_eq("Generated public key matches", keypair.raw_public_key(), vars.get_req_bin("PublicKey")); return result; @@ -431,13 +451,14 @@ std::vector xmss_wots_derivation_method() { const Botan::XMSS_PrivateKey sk(oid, 0, private_seed, prf, root, public_seed); auto skbytes = sk.raw_private_key(); - // The derivation method is the final byte of the encoding - skbytes.back() = 0; + // The derivation method is the final byte of the legacy fields + auto& method = skbytes.at(Botan::XMSS_Parameters::from_id(oid)._raw_private_key_size() - 1); + method = 0; result.test_throws("decoding rejects method 0", [&] { const Botan::XMSS_PrivateKey loaded(Botan::AlgorithmIdentifier(), skbytes); }); - skbytes.back() = 3; + method = 3; result.test_throws("decoding rejects method 3", [&] { const Botan::XMSS_PrivateKey loaded(Botan::AlgorithmIdentifier(), skbytes); }); @@ -639,6 +660,529 @@ std::vector xmss_fork_safety() { #endif } +uint32_t u32_at(std::span bytes, size_t offset) { + if(offset + sizeof(uint32_t) > bytes.size()) { + throw Test_Error("XMSS private key encoding is shorter than expected"); + } + return Botan::load_be(bytes.subspan(offset).first()); +} + +// The first four bytes of an XMSS signature encode the leaf index +uint32_t xmss_signature_index(std::span sig) { + return Botan::load_be(sig.first()); +} + +/** + * Offsets within an XMSS private key in the current format + */ +struct XMSS_SK_Layout final { + size_t n; + size_t root; + size_t leaf_index; + size_t prf; + size_t private_seed; + size_t legacy_end; + size_t section_count; + size_t treetop; + size_t row; + size_t row_size; +}; + +XMSS_SK_Layout xmss_sk_layout(const Botan::XMSS_Parameters& params) { + XMSS_SK_Layout layout{}; + layout.n = params.element_size(); + layout.root = sizeof(uint32_t); + layout.leaf_index = layout.root + 2 * layout.n; + layout.prf = layout.leaf_index + sizeof(uint32_t); + layout.private_seed = layout.prf + layout.n; + layout.legacy_end = params._raw_private_key_size(); + layout.section_count = layout.legacy_end; + // A freshly generated key has a single section, holding the treetop + layout.treetop = layout.section_count + sizeof(uint32_t); + layout.row = layout.treetop + 2 * sizeof(uint32_t); + layout.row_size = Botan::Merkle_Treetop::row_size(static_cast(params.tree_height()), layout.n); + return layout; +} + +/** + * Tests of the private key encoding, and the tree data cached in the key. + */ +class XMSS_Encoding_Test_Base : public Test { + protected: + static constexpr auto Params = Botan::XMSS_Parameters::XMSS_SHA2_10_256; + + static Botan::XMSS_Parameters params() { return Botan::XMSS_Parameters::from_id(Params); } + + std::vector message() const { return {0xde, 0xad, 0xbe, 0xef}; } + + std::vector sign(const Botan::Private_Key& sk) const { + Botan::PK_Signer signer(sk, Test::rng(), Botan::PK_Signature_Options()); + return signer.sign_message(message(), Test::rng()); + } + + bool verify(const Botan::Public_Key& pk, std::span sig) const { + Botan::PK_Verifier verifier(pk, Botan::PK_Signature_Options()); + return verifier.verify_message(message(), sig); + } + + static Botan::AlgorithmIdentifier xmss_sk_alg_id(std::string_view oid_name) { + return Botan::AlgorithmIdentifier(Botan::OID::from_string(oid_name), + Botan::AlgorithmIdentifier::USE_EMPTY_PARAM); + } + + static Botan::XMSS_PrivateKey load(std::span bytes) { + return Botan::XMSS_PrivateKey(xmss_sk_alg_id("XMSS-Private-Key"), bytes); + } + + static Botan::XMSS_PrivateKey load_legacy(std::span bytes) { + return Botan::XMSS_PrivateKey(xmss_sk_alg_id("XMSS"), bytes); + } + + /** + * The fields of the legacy format, which the current format starts with + */ + static std::vector legacy_fields(std::span bytes) { + const auto layout = xmss_sk_layout(params()); + return std::vector(bytes.begin(), bytes.begin() + layout.legacy_end); + } + + /** + * The legacy encoding, wrapped in an OCTET STRING as written by older versions + */ + static std::vector legacy_encoding(std::span bytes) { + return Botan::DER_Encoder() + .encode(legacy_fields(bytes), Botan::ASN1_Type::OctetString) + .get_contents_unlocked(); + } + + static std::span treetop_row(std::span bytes) { + const auto layout = xmss_sk_layout(params()); + return bytes.subspan(layout.row, layout.row_size); + } + + Test::Result test_current_encoding() { + Test::Result result("XMSS private key encoding"); + + const auto layout = xmss_sk_layout(params()); + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + + result.test_str_eq( + "private key OID", sk.pkcs8_algorithm_identifier().oid().to_string(), "1.3.6.1.4.1.25258.1.20"); + + const auto bytes = sk.private_key_bits(); + result.test_bin_eq("private key bits are the raw private key", sk.raw_private_key(), bytes); + result.test_u32_eq("treetop is cached after key generation", u32_at(bytes, layout.section_count), 1); + result.test_u32_eq("treetop section tag", u32_at(bytes, layout.treetop), 1); + result.test_u32_eq("treetop section length", + u32_at(bytes, layout.treetop + sizeof(uint32_t)), + static_cast(layout.row_size)); + result.test_sz_eq("treetop holds all 2^10 leaves", layout.row_size, 1024 * layout.n); + result.test_sz_eq("encoding has no trailing data", bytes.size(), layout.row + layout.row_size); + + const auto loaded = load(bytes); + result.test_bin_eq("loaded key has the same public key", loaded.public_key_bits(), sk.public_key_bits()); + result.test_bin_eq("encoding round trips", loaded.private_key_bits(), bytes); + + result.test_is_true("signature of generated key is valid", verify(sk, sign(sk))); + const auto sig = sign(loaded); + result.test_u32_eq("loaded key continues at the next index", xmss_signature_index(sig), 1); + result.test_is_true("signature of loaded key is valid", verify(sk, sig)); + + // A key constructed from its components only computes the tree when signing + const auto field = [&](size_t offset) { + return Botan::secure_vector(bytes.begin() + offset, bytes.begin() + offset + layout.n); + }; + const Botan::XMSS_PrivateKey from_components(Params, + 2, + field(layout.private_seed), + field(layout.prf), + field(layout.root), + field(layout.root + layout.n)); + const auto uncached = from_components.private_key_bits(); + result.test_u32_eq("no cached tree before signing", u32_at(uncached, layout.section_count), 0); + result.test_sz_eq("encoding without cached tree", uncached.size(), layout.section_count + sizeof(uint32_t)); + result.test_is_true("key without cached tree signs validly", verify(sk, sign(from_components))); + result.test_bin_eq( + "signing caches the treetop", treetop_row(from_components.private_key_bits()), treetop_row(bytes)); + + return result; + } + + Test::Result test_legacy_encoding() { + Test::Result result("XMSS legacy private key encoding"); + + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + sign(sk); + + const auto legacy = legacy_encoding(sk.private_key_bits()); + const auto loaded = load_legacy(legacy); + result.test_bin_eq("legacy key has the same public key", loaded.public_key_bits(), sk.public_key_bits()); + + const auto sig = sign(loaded); + result.test_u32_eq("legacy key continues at the next index", xmss_signature_index(sig), 1); + result.test_is_true("signature of legacy key is valid", verify(sk, sig)); + + const auto reencoded = loaded.private_key_bits(); + const auto layout = xmss_sk_layout(params()); + result.test_u32_eq("re-encoded legacy key caches the treetop", u32_at(reencoded, layout.section_count), 1); + result.test_bin_eq("re-encoded legacy key starts with the legacy fields", + legacy_fields(reencoded), + legacy_fields(sk.private_key_bits())); + result.test_bin_eq("re-encoded treetop", treetop_row(reencoded), treetop_row(sk.private_key_bits())); + + result.test_no_throw("legacy fields without an OCTET STRING", [&] { + const auto key = load_legacy(legacy_fields(sk.private_key_bits())); + result.test_bin_eq("same public key", key.public_key_bits(), sk.public_key_bits()); + }); + + // A PKCS #8 structure as written by older versions + const auto pkcs8 = Botan::DER_Encoder() + .start_sequence() + .encode(size_t(0)) + .encode(xmss_sk_alg_id("XMSS")) + .encode(legacy, Botan::ASN1_Type::OctetString) + .end_cons() + .get_contents_unlocked(); + const auto from_pkcs8 = Botan::PKCS8::load_key(pkcs8); + result.test_bin_eq( + "legacy PKCS #8 key has the same public key", from_pkcs8->public_key_bits(), sk.public_key_bits()); + result.test_is_true("signature of legacy PKCS #8 key is valid", verify(sk, sign(*from_pkcs8))); + + return result; + } + + Test::Result test_algorithm_identifiers() { + Test::Result result("XMSS private key algorithm identifiers"); + + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + const auto current = sk.private_key_bits(); + const auto legacy = legacy_encoding(current); + + const auto from_pkcs8 = Botan::PKCS8::load_key(sk.private_key_info()); + result.test_bin_eq("PKCS #8 round trip", from_pkcs8->private_key_bits(), current); + + const auto loads_raw = [&](std::string_view what, std::span bytes) { + result.test_no_throw(what, [&] { + const Botan::XMSS_PrivateKey key(Botan::AlgorithmIdentifier(), bytes); + result.test_bin_eq("same public key", key.public_key_bits(), sk.public_key_bits()); + }); + }; + + loads_raw("raw bytes in the current format", current); + loads_raw("raw bytes in the legacy format", legacy); + loads_raw("raw bytes in the legacy format without an OCTET STRING", legacy_fields(current)); + + result.test_throws("legacy OID with the current format", [&] { load_legacy(current); }); + result.test_throws("current OID with the legacy format", + [&] { load(legacy_fields(current)); }); + result.test_throws("private key OID with parameters", [&] { + const Botan::XMSS_PrivateKey key(Botan::AlgorithmIdentifier(Botan::OID::from_string("XMSS-Private-Key"), + Botan::AlgorithmIdentifier::USE_NULL_PARAM), + current); + }); + result.test_throws( + "unrelated OID", [&] { const Botan::XMSS_PrivateKey key(xmss_sk_alg_id("RSA"), current); }); + + return result; + } + + Test::Result test_root_is_taken_from_encoding() { + Test::Result result("XMSS root is not recomputed on load"); + + const auto layout = xmss_sk_layout(params()); + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + + auto bytes = sk.private_key_bits(); + bytes.at(layout.private_seed) ^= 0x01; + + const auto corrupted = load(bytes); + result.test_bin_eq( + "public key is taken from the stored root", corrupted.public_key_bits(), sk.public_key_bits()); + + result.test_is_true("strong key check of a valid key passes", sk.check_key(Test::rng(), true)); + result.test_is_true("weak key check does not compute the tree", corrupted.check_key(Test::rng(), false)); + result.test_is_true("strong key check detects a seed not matching the root", + !corrupted.check_key(Test::rng(), true)); + + result.test_throws("a signature not matching the root is not released", + [&] { sign(corrupted); }); + result.test_throws("a seed not matching the root is detected once recomputed", + [&] { sign(corrupted); }); + + return result; + } + + Test::Result test_corrupt_cache_is_discarded() { + Test::Result result("XMSS corrupted cache data"); + + const auto layout = xmss_sk_layout(params()); + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + const auto bytes = sk.private_key_bits(); + + const auto signs_validly_after_flipping = [&](std::string_view what, size_t offset) { + auto corrupted = bytes; + corrupted.at(offset) ^= 0x01; + const auto loaded = load(corrupted); + const auto sig = sign(loaded); + result.test_is_true(Botan::fmt("{}: signature is valid", what), verify(sk, sig)); + result.test_bin_eq(Botan::fmt("{}: treetop is recomputed", what), + treetop_row(loaded.private_key_bits()), + treetop_row(bytes)); + }; + + signs_validly_after_flipping("first leaf", layout.row); + signs_validly_after_flipping("last leaf", layout.row + layout.row_size - 1); + + auto corrupted_root = bytes; + corrupted_root.at(layout.root) ^= 0x01; + const auto loaded = load(corrupted_root); + result.test_throws("signing with a corrupted root fails", [&] { sign(loaded); }); + + return result; + } + + Test::Result test_unknown_sections_are_ignored() { + Test::Result result("XMSS unknown private key sections"); + + const auto layout = xmss_sk_layout(params()); + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + + auto bytes = sk.private_key_bits(); + Botan::store_be(u32_at(bytes, layout.section_count) + 1, bytes.data() + layout.section_count); + const auto unknown = Botan::concat>( + Botan::store_be(uint32_t(0x7fffffff)), Botan::store_be(uint32_t(3)), std::array{1, 2, 3}); + bytes.insert(bytes.end(), unknown.begin(), unknown.end()); + + const auto loaded = load(bytes); + result.test_is_true("key with an unknown section signs validly", verify(sk, sign(loaded))); + + return result; + } + + Test::Result test_malformed_encodings_are_rejected() { + Test::Result result("XMSS malformed private key encodings"); + + const auto layout = xmss_sk_layout(params()); + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + const auto bytes = sk.private_key_bits(); + + const auto rejects = [&](std::string_view what, const auto& patch) { + auto patched = bytes; + patch(patched); + result.test_throws(what, [&] { load(patched); }); + }; + + rejects("trailing data", [](auto& b) { b.push_back(0); }); + rejects("truncated", [](auto& b) { b.pop_back(); }); + rejects("missing section", [&](auto& b) { Botan::store_be(uint32_t(2), b.data() + layout.section_count); }); + rejects("wrong treetop length", [&](auto& b) { + Botan::store_be(static_cast(layout.row_size - 1), b.data() + layout.treetop + sizeof(uint32_t)); + }); + rejects("two treetops", [&](auto& b) { + Botan::store_be(uint32_t(2), b.data() + layout.section_count); + const std::vector section(b.begin() + layout.treetop, b.end()); + b.insert(b.end(), section.begin(), section.end()); + }); + rejects("unknown WOTS+ derivation method", [&](auto& b) { b.at(layout.legacy_end - 1) = 0; }); + + return result; + } + + Test::Result test_subtrees() { + Test::Result result("XMSS trees with subtrees"); + + // Trees higher than 10 store their nodes down to height h - 10 and + // recompute the subtrees below as needed + const auto params16 = Botan::XMSS_Parameters::from_id(Botan::XMSS_Parameters::XMSS_SHA2_16_256); + const auto layout = xmss_sk_layout(params16); + result.test_u32_eq("subtree height", Botan::Merkle_Treetop::subtree_height(16), 6); + + const Botan::XMSS_PrivateKey sk(params16.oid(), Test::rng()); + auto bytes = sk.private_key_bits(); + result.test_u32_eq("treetop is cached", u32_at(bytes, layout.section_count), 1); + result.test_sz_eq("treetop holds 2^10 nodes", layout.row_size, 1024 * layout.n); + result.test_is_true("signature using the subtree of key generation is valid", verify(sk, sign(sk))); + + // Index 63 is the last leaf of the first subtree + Botan::store_be(uint32_t(63), bytes.data() + layout.leaf_index); + const auto loaded = load(bytes); + for(const uint32_t idx : {uint32_t(63), uint32_t(64)}) { + const auto sig = sign(loaded); + result.test_u32_eq("signature index", xmss_signature_index(sig), idx); + result.test_is_true("signature using a recomputed subtree is valid", verify(sk, sig)); + } + + const auto reloaded = load(loaded.private_key_bits()); + const auto sig = sign(reloaded); + result.test_u32_eq("reloaded key continues at the next index", xmss_signature_index(sig), 65); + result.test_is_true("signature of reloaded key is valid", verify(sk, sig)); + + return result; + } + + #if defined(BOTAN_TARGET_OS_HAS_THREADS) + Test::Result test_concurrent_signing() { + Test::Result result("XMSS concurrent signing with separately loaded keys"); + + const Botan::XMSS_PrivateKey sk(Params, Test::rng()); + const auto bytes = sk.private_key_bits(); + const auto legacy = legacy_encoding(bytes); + + // More threads than key objects, so some objects are shared between + // threads. Half of the objects are loaded from the legacy encoding. + constexpr size_t key_objects = 4; + constexpr size_t threads = 8; + constexpr size_t sigs_per_thread = 20; + constexpr size_t total_sigs = threads * sigs_per_thread; + + std::vector> keys; + for(size_t i = 0; i != key_objects; ++i) { + keys.push_back(std::make_unique((i % 2 == 0) ? load(bytes) : load_legacy(legacy))); + } + + const auto thread_message = [](size_t t, size_t i) { + return std::vector{static_cast(t), static_cast(i)}; + }; + + std::vector>>> futures; + futures.reserve(threads); + for(size_t t = 0; t != threads; ++t) { + futures.push_back(std::async(std::launch::async, [&, t]() { + auto thread_rng = Test::new_rng(Botan::fmt("{} thread {}", result.who(), t)); + Botan::PK_Signer signer(*keys[t % key_objects], *thread_rng, Botan::PK_Signature_Options()); + std::vector> sigs; + for(size_t i = 0; i != sigs_per_thread; ++i) { + sigs.push_back(signer.sign_message(thread_message(t, i), *thread_rng)); + } + return sigs; + })); + } + + Botan::PK_Verifier verifier(sk, Botan::PK_Signature_Options()); + std::set indices; + for(size_t t = 0; t != threads; ++t) { + try { + const auto sigs = futures[t].get(); + for(size_t i = 0; i != sigs.size(); ++i) { + if(!verifier.verify_message(thread_message(t, i), sigs[i])) { + result.test_failure(Botan::fmt("signature {} of thread {} is invalid", i, t)); + } + if(!indices.insert(xmss_signature_index(sigs[i])).second) { + result.test_failure(Botan::fmt("signature {} of thread {} reuses an index", i, t)); + } + } + } catch(const std::exception& e) { + result.test_failure(Botan::fmt("thread {} failed", t), e.what()); + } + } + + result.test_sz_eq("each signature used its own index", indices.size(), total_sigs); + result.test_is_true("indices are consecutive", !indices.empty() && *indices.rbegin() == total_sigs - 1); + result.test_opt_u64_eq("all copies share the state", keys[1]->remaining_operations(), 1024 - total_sigs); + + const auto reloaded = load(keys[1]->private_key_bits()); + const auto sig = sign(reloaded); + result.test_u32_eq("reloaded key continues after all threads", xmss_signature_index(sig), total_sigs); + result.test_is_true("signature of reloaded key is valid", verify(sk, sig)); + + return result; + } + #endif + + #if defined(BOTAN_HAS_THREAD_UTILS) + /** + * Computing a tree uses the thread pool, whose threads may themselves be + * signing with the same key. That is the case if the application provides + * a Work_Executor running on its own threads. Those threads must not wait + * for a tree being computed elsewhere, which in turn waits for them. + */ + Test::Result test_signing_within_pool_work() { + Test::Result result("XMSS signing within thread pool work"); + + // A key loaded from the legacy encoding computes its tree when it first signs + const Botan::XMSS_PrivateKey generated(Params, Test::rng()); + const auto sk = load_legacy(legacy_encoding(generated.private_key_bits())); + + const auto sign_as = [&](size_t t) { + auto thread_rng = Test::new_rng(Botan::fmt("{} thread {}", result.who(), t)); + Botan::PK_Signer signer(sk, *thread_rng, Botan::PK_Signature_Options()); + return signer.sign_message(std::vector{static_cast(t)}, *thread_rng); + }; + + auto& pool = Botan::Thread_Pool::global_instance(); + const size_t workers = pool.worker_count(); + const auto remaining = sk.remaining_operations(); + + auto outside = std::async(std::launch::async, sign_as, workers); + + // Once it has reserved its leaf, that thread is computing the tree + while(sk.remaining_operations() == remaining && + outside.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { + std::this_thread::yield(); + } + + std::vector>> in_pool; + in_pool.reserve(workers); + for(size_t t = 0; t != workers; ++t) { + in_pool.push_back(pool.run(sign_as, t)); + } + + Botan::PK_Verifier verifier(sk, Botan::PK_Signature_Options()); + std::set indices; + for(size_t t = 0; t != workers + 1; ++t) { + try { + const auto sig = (t == workers) ? outside.get() : in_pool[t].get(); + result.test_is_true("signature is valid", + verifier.verify_message(std::vector{static_cast(t)}, sig)); + indices.insert(xmss_signature_index(sig)); + } catch(const std::exception& e) { + result.test_failure(Botan::fmt("thread {} failed", t), e.what()); + } + } + + result.test_sz_eq("each signature used its own index", indices.size(), workers + 1); + + return result; + } + #endif +}; + +class XMSS_Encoding_Test final : public XMSS_Encoding_Test_Base { + public: + std::vector run() final { + std::vector results = {test_current_encoding(), + test_legacy_encoding(), + test_algorithm_identifiers(), + test_root_is_taken_from_encoding(), + test_corrupt_cache_is_discarded(), + test_unknown_sections_are_ignored(), + test_malformed_encodings_are_rejected()}; + + #if defined(BOTAN_TARGET_OS_HAS_THREADS) + results.push_back(test_concurrent_signing()); + #endif + + #if defined(BOTAN_HAS_THREAD_UTILS) + results.push_back(test_signing_within_pool_work()); + #endif + + return results; + } +}; + +/** + * Separate from XMSS_Encoding_Test, since computing a tree of height 16 is slow. + */ +class XMSS_Subtree_Test final : public XMSS_Encoding_Test_Base { + public: + std::vector run() final { + if(!Test::run_long_tests()) { + return {}; + } + return {test_subtrees()}; + } +}; + BOTAN_REGISTER_TEST("pubkey", "xmss_sign", XMSS_Signature_Tests); BOTAN_REGISTER_TEST("pubkey", "xmss_verify", XMSS_Signature_Verify_Tests); BOTAN_REGISTER_TEST("pubkey", "xmss_verify_invalid", XMSS_Signature_Verify_Invalid_Tests); @@ -654,6 +1198,8 @@ BOTAN_REGISTER_TEST_FN("pubkey", xmss_signature_length, xmss_check_key, xmss_fork_safety); +BOTAN_REGISTER_TEST("pubkey", "xmss_encoding", XMSS_Encoding_Test); +BOTAN_REGISTER_TEST("pubkey", "xmss_subtrees", XMSS_Subtree_Test); #endif