Botan 3.11.0
Crypto and TLS for C&
xmss_privatekey.cpp
Go to the documentation of this file.
1/*
2 * XMSS Private Key
3 * An XMSS: Extended Hash-Based Signature private key.
4 * The XMSS private key does not support the X509 and PKCS7 standard. Instead
5 * the raw format described in [1] is used.
6 *
7 * [1] XMSS: Extended Hash-Based Signatures,
8 * Request for Comments: 8391
9 * Release: May 2018.
10 * https://datatracker.ietf.org/doc/rfc8391/
11 *
12 * (C) 2016,2017,2018 Matthias Gierlings
13 * (C) 2019,2026 Jack Lloyd
14 * (C) 2023 René Meusel - Rohde & Schwarz Cybersecurity
15 *
16 * Botan is released under the Simplified BSD License (see license.txt)
17 **/
18
19#include <botan/xmss.h>
20
21#include <botan/ber_dec.h>
22#include <botan/der_enc.h>
23#include <botan/rng.h>
24#include <botan/internal/buffer_slicer.h>
25#include <botan/internal/concat_util.h>
26#include <botan/internal/int_utils.h>
27#include <botan/internal/loadstor.h>
28#include <botan/internal/stateful_key_index_registry.h>
29#include <botan/internal/xmss_common_ops.h>
30#include <botan/internal/xmss_hash.h>
31#include <botan/internal/xmss_signature_operation.h>
32
33#if defined(BOTAN_HAS_THREAD_UTILS)
34 #include <botan/internal/thread_pool.h>
35#endif
36
37namespace Botan {
38
39namespace {
40
41// fall back to raw decoding for previous versions, which did not encode an OCTET STRING
42secure_vector<uint8_t> extract_raw_private_key(std::span<const uint8_t> key_bits, const XMSS_Parameters& xmss_params) {
44
45 // The public part of the input key bits was already parsed, so we can
46 // decide depending on the buffer length whether this must be BER decoded.
47 if(key_bits.size() == xmss_params.raw_private_key_size() ||
48 key_bits.size() == xmss_params.raw_legacy_private_key_size()) {
49 raw_key.assign(key_bits.begin(), key_bits.end());
50 } else {
52 }
53
54 return raw_key;
55}
56
57} // namespace
58
59class XMSS_PrivateKey_Internal {
60 public:
61 XMSS_PrivateKey_Internal(const XMSS_Parameters& xmss_params,
62 const XMSS_WOTS_Parameters& wots_params,
63 WOTS_Derivation_Method wots_derivation_method,
64 RandomNumberGenerator& rng) :
65 m_xmss_params(xmss_params),
66 m_wots_params(wots_params),
67 m_wots_derivation_method(wots_derivation_method),
68 m_prf(rng.random_vec(xmss_params.element_size())),
69 m_private_seed(rng.random_vec(xmss_params.element_size())),
70 m_keyid(Stateful_Key_Index_Registry::KeyId("XMSS", m_xmss_params.oid(), m_private_seed, m_prf)) {}
71
72 XMSS_PrivateKey_Internal(const XMSS_Parameters& xmss_params,
73 const XMSS_WOTS_Parameters& wots_params,
74 WOTS_Derivation_Method wots_derivation_method,
75 secure_vector<uint8_t> private_seed,
77 m_xmss_params(xmss_params),
78 m_wots_params(wots_params),
79 m_wots_derivation_method(wots_derivation_method),
80 m_prf(std::move(prf)),
81 m_private_seed(std::move(private_seed)),
82 m_keyid(Stateful_Key_Index_Registry::KeyId("XMSS", m_xmss_params.oid(), m_private_seed, m_prf)) {}
83
84 XMSS_PrivateKey_Internal(const XMSS_Parameters& xmss_params,
85 const XMSS_WOTS_Parameters& wots_params,
86 std::span<const uint8_t> key_bits) :
87 m_xmss_params(xmss_params), m_wots_params(wots_params), m_keyid(/* initialized later*/) {
88 /*
89 The code requires sizeof(size_t) >= ceil(tree_height / 8)
90
91 Maximum supported tree height is 20, ceil(20/8) == 3, so 4 byte
92 size_t is sufficient for all defined parameters, or even a
93 (hypothetical) tree height 32, which would be extremely slow to
94 compute.
95 */
96 static_assert(sizeof(size_t) >= 4, "size_t is big enough to support leaf index");
97
98 const secure_vector<uint8_t> raw_key = extract_raw_private_key(key_bits, xmss_params);
99
100 if(raw_key.size() != m_xmss_params.raw_private_key_size() &&
101 raw_key.size() != m_xmss_params.raw_legacy_private_key_size()) {
102 throw Decoding_Error("Invalid XMSS private key size");
103 }
104
105 BufferSlicer s(raw_key);
106
107 // We're not interested in the public key here
108 s.skip(m_xmss_params.raw_public_key_size());
109
110 auto unused_leaf_bytes = s.take(sizeof(uint32_t));
111 const size_t unused_leaf = load_be<uint32_t>(unused_leaf_bytes.data(), 0);
112 if(unused_leaf >= (1ULL << m_xmss_params.tree_height())) {
113 throw Decoding_Error("XMSS private key leaf index out of bounds");
114 }
115
116 m_prf = s.copy_as_secure_vector(m_xmss_params.element_size());
117 m_private_seed = s.copy_as_secure_vector(m_xmss_params.element_size());
118
119 m_keyid = Stateful_Key_Index_Registry::KeyId("XMSS", m_xmss_params.oid(), m_private_seed, m_prf);
120
121 // Note m_keyid must be initialized before set_unused_leaf_index is called!
122 set_unused_leaf_index(unused_leaf);
123
124 // Legacy keys generated prior to Botan 3.x don't feature a
125 // WOTS+ key derivation method encoded in their private key.
126 m_wots_derivation_method =
127 (s.empty()) ? WOTS_Derivation_Method::Botan2x : static_cast<WOTS_Derivation_Method>(s.take(1).front());
128
129 BOTAN_ASSERT_NOMSG(s.empty());
130 }
131
132 secure_vector<uint8_t> serialize(std::vector<uint8_t> raw_public_key) const {
133 std::vector<uint8_t> unused_index(4);
134 store_be(static_cast<uint32_t>(unused_leaf_index()), unused_index.data());
135
136 std::vector<uint8_t> wots_derivation_method;
137 wots_derivation_method.push_back(static_cast<uint8_t>(m_wots_derivation_method));
138
140 raw_public_key, unused_index, m_prf, m_private_seed, wots_derivation_method);
141 }
142
143 const secure_vector<uint8_t>& prf_value() const { return m_prf; }
144
145 const secure_vector<uint8_t>& private_seed() { return m_private_seed; }
146
147 const XMSS_WOTS_Parameters& wots_parameters() { return m_wots_params; }
148
149 WOTS_Derivation_Method wots_derivation_method() const { return m_wots_derivation_method; }
150
151 void set_unused_leaf_index(size_t idx) {
152 if(idx >= (1ULL << m_xmss_params.tree_height())) {
153 throw Decoding_Error("XMSS private key leaf index out of bounds");
154 } else {
156 }
157 }
158
159 size_t reserve_unused_leaf_index() {
160 const uint64_t idx = Stateful_Key_Index_Registry::global().reserve_next_index(m_keyid);
161 if(idx >= m_xmss_params.total_number_of_signatures()) {
162 throw Decoding_Error("XMSS private key, one time signatures exhausted");
163 }
164 // Cast is safe even on 32 bit since total_number_of_signatures will be less
165 return static_cast<size_t>(idx);
166 }
167
168 size_t unused_leaf_index() const {
169 const uint64_t idx = Stateful_Key_Index_Registry::global().current_index(m_keyid);
170 return checked_cast_to<size_t>(idx);
171 }
172
173 uint64_t remaining_signatures() const {
174 const size_t max = m_xmss_params.total_number_of_signatures();
176 }
177
178 private:
179 XMSS_Parameters m_xmss_params;
180 XMSS_WOTS_Parameters m_wots_params;
181 WOTS_Derivation_Method m_wots_derivation_method;
182
184 secure_vector<uint8_t> m_private_seed;
185 Stateful_Key_Index_Registry::KeyId m_keyid;
186};
187
188XMSS_PrivateKey::XMSS_PrivateKey(std::span<const uint8_t> key_bits) :
189 XMSS_PublicKey(key_bits),
190 m_private(std::make_shared<XMSS_PrivateKey_Internal>(m_xmss_params, m_wots_params, key_bits)) {}
191
195 XMSS_PublicKey(xmss_algo_id, rng),
196 m_private(std::make_shared<XMSS_PrivateKey_Internal>(m_xmss_params, m_wots_params, wots_derivation_method, rng)) {
197 const XMSS_Address adrs;
199 m_root = tree_hash(0, XMSS_PublicKey::m_xmss_params.tree_height(), adrs, hash);
200}
201
203 size_t idx_leaf,
204 secure_vector<uint8_t> wots_priv_seed,
209 XMSS_PublicKey(xmss_algo_id, std::move(root), std::move(public_seed)),
210 m_private(std::make_shared<XMSS_PrivateKey_Internal>(
211 m_xmss_params, m_wots_params, wots_derivation_method, std::move(wots_priv_seed), std::move(prf))) {
212 m_private->set_unused_leaf_index(idx_leaf);
213 BOTAN_ARG_CHECK(m_private->prf_value().size() == m_xmss_params.element_size(),
214 "XMSS: unexpected byte length of PRF value");
215 BOTAN_ARG_CHECK(m_private->private_seed().size() == m_xmss_params.element_size(),
216 "XMSS: unexpected byte length of private seed");
217}
218
219secure_vector<uint8_t> XMSS_PrivateKey::tree_hash(size_t start_idx,
220 size_t target_node_height,
221 const XMSS_Address& adrs,
222 XMSS_Hash& hash) const {
223 BOTAN_ASSERT_NOMSG(target_node_height <= 30);
224 BOTAN_ASSERT((start_idx % (static_cast<size_t>(1) << target_node_height)) == 0,
225 "Start index must be divisible by 2^{target node height}.");
226
227#if defined(BOTAN_HAS_THREAD_UTILS)
228 // determine number of parallel tasks to split the tree_hashing into.
229
231
232 const size_t split_level = std::min(target_node_height, thread_pool.worker_count());
233
234 // skip parallelization overhead for leaf nodes.
235 if(split_level == 0) {
237 XMSS_Address subtree_addr(adrs);
238 tree_hash_subtree(result, start_idx, target_node_height, subtree_addr, hash);
239 return result;
240 }
241
242 const size_t subtrees = static_cast<size_t>(1) << split_level;
243 const size_t last_idx = (static_cast<size_t>(1) << (target_node_height)) + start_idx;
244 const size_t offs = (last_idx - start_idx) / subtrees;
245 // this cast cannot overflow because target_node_height is limited
246 uint8_t level = static_cast<uint8_t>(split_level); // current level in the tree
247
248 BOTAN_ASSERT((last_idx - start_idx) % subtrees == 0,
249 "Number of worker threads in tree_hash need to divide range "
250 "of calculated nodes.");
251
252 std::vector<secure_vector<uint8_t>> nodes(subtrees,
254 std::vector<XMSS_Address> node_addresses(subtrees, adrs);
255 std::vector<XMSS_Hash> xmss_hash(subtrees, hash);
256 std::vector<std::future<void>> work;
257
258 // Calculate multiple subtrees in parallel.
259 for(size_t i = 0; i < subtrees; i++) {
260 using tree_hash_subtree_fn_t =
261 void (XMSS_PrivateKey::*)(secure_vector<uint8_t>&, size_t, size_t, XMSS_Address&, XMSS_Hash&) const;
262
263 const tree_hash_subtree_fn_t work_fn = &XMSS_PrivateKey::tree_hash_subtree;
264
265 work.push_back(thread_pool.run(work_fn,
266 this,
267 std::ref(nodes[i]),
268 start_idx + i * offs,
269 target_node_height - split_level,
270 std::ref(node_addresses[i]),
271 std::ref(xmss_hash[i])));
272 }
273
274 for(auto& w : work) {
275 w.get();
276 }
277 work.clear();
278
279 // Parallelize the top tree levels horizontally
280 while(level-- > 1) {
281 std::vector<secure_vector<uint8_t>> ro_nodes(nodes.begin(),
282 nodes.begin() + (static_cast<size_t>(1) << (level + 1)));
283
284 for(size_t i = 0; i < (static_cast<size_t>(1) << level); i++) {
285 BOTAN_ASSERT_NOMSG(xmss_hash.size() > i);
286
287 node_addresses[i].set_tree_height(static_cast<uint32_t>(target_node_height - (level + 1)));
288 node_addresses[i].set_tree_index((node_addresses[2 * i + 1].get_tree_index() - 1) >> 1);
289
290 work.push_back(thread_pool.run(&XMSS_Common_Ops::randomize_tree_hash,
291 std::ref(nodes[i]),
292 std::cref(ro_nodes[2 * i]),
293 std::cref(ro_nodes[2 * i + 1]),
294 node_addresses[i],
295 std::cref(this->public_seed()),
296 std::ref(xmss_hash[i]),
297 std::cref(m_xmss_params)));
298 }
299
300 for(auto& w : work) {
301 w.get();
302 }
303 work.clear();
304 }
305
306 // Avoid creation an extra thread to calculate root node.
307 node_addresses[0].set_tree_height(static_cast<uint32_t>(target_node_height - 1));
308 node_addresses[0].set_tree_index((node_addresses[1].get_tree_index() - 1) >> 1);
310 nodes[0], nodes[0], nodes[1], node_addresses[0], this->public_seed(), hash, m_xmss_params);
311 return nodes[0];
312#else
314 XMSS_Address subtree_addr(adrs);
315 tree_hash_subtree(result, start_idx, target_node_height, subtree_addr, hash);
316 return result;
317#endif
318}
319
320void XMSS_PrivateKey::tree_hash_subtree(secure_vector<uint8_t>& result,
321 size_t start_idx,
322 size_t target_node_height,
323 XMSS_Address& adrs,
324 XMSS_Hash& hash) const {
325 const secure_vector<uint8_t>& seed = this->public_seed();
326
327 std::vector<secure_vector<uint8_t>> nodes(target_node_height + 1,
329
330 // node stack, holds all nodes on stack and one extra "pending" node. This
331 // temporary node referred to as "node" in the XMSS standard document stays
332 // a pending element, meaning it is not regarded as element on the stack
333 // until level is increased.
334 std::vector<uint8_t> node_levels(target_node_height + 1);
335
336 uint8_t level = 0; // current level on the node stack.
337 const size_t last_idx = (static_cast<size_t>(1) << target_node_height) + start_idx;
338
339 for(size_t i = start_idx; i < last_idx; i++) {
341 adrs.set_ots_address(static_cast<uint32_t>(i));
342
343 const XMSS_WOTS_PublicKey pk = this->wots_public_key_for(adrs, hash);
344
346 adrs.set_ltree_address(static_cast<uint32_t>(i));
347 XMSS_Common_Ops::create_l_tree(nodes[level], pk.key_data(), adrs, seed, hash, m_xmss_params);
348 node_levels[level] = 0;
349
351 adrs.set_tree_height(0);
352 adrs.set_tree_index(static_cast<uint32_t>(i));
353
354 while(level > 0 && node_levels[level] == node_levels[level - 1]) {
355 adrs.set_tree_index(((adrs.get_tree_index() - 1) >> 1));
357 nodes[level - 1], nodes[level - 1], nodes[level], adrs, seed, hash, m_xmss_params);
358 node_levels[level - 1]++;
359 level--; //Pop stack top element
360 adrs.set_tree_height(adrs.get_tree_height() + 1);
361 }
362 level++; //push temporary node to stack
363 }
364 result = nodes[level - 1];
365}
366
367XMSS_WOTS_PublicKey XMSS_PrivateKey::wots_public_key_for(const XMSS_Address& adrs, XMSS_Hash& hash) const {
368 const auto private_key = wots_private_key_for(adrs, hash);
369 return XMSS_WOTS_PublicKey(m_private->wots_parameters(), m_public_seed, private_key, adrs, hash);
370}
371
372XMSS_WOTS_PrivateKey XMSS_PrivateKey::wots_private_key_for(const XMSS_Address& adrs, XMSS_Hash& hash) const {
373 switch(wots_derivation_method()) {
375 return XMSS_WOTS_PrivateKey(
376 m_private->wots_parameters(), m_public_seed, m_private->private_seed(), adrs, hash);
378 return XMSS_WOTS_PrivateKey(m_private->wots_parameters(), m_private->private_seed(), adrs, hash);
379 }
380
381 throw Invalid_State("WOTS derivation method is out of the enum's range");
382}
383
387
388size_t XMSS_PrivateKey::reserve_unused_leaf_index() {
389 return m_private->reserve_unused_leaf_index();
390}
391
393 return m_private->unused_leaf_index();
394}
395
397 return checked_cast_to<size_t>(m_private->remaining_signatures());
398}
399
400std::optional<uint64_t> XMSS_PrivateKey::remaining_operations() const {
401 return m_private->remaining_signatures();
402}
403
404const secure_vector<uint8_t>& XMSS_PrivateKey::prf_value() const {
405 return m_private->prf_value();
406}
407
409 return m_private->serialize(raw_public_key());
410}
411
413 return m_private->wots_derivation_method();
414}
415
416std::unique_ptr<Public_Key> XMSS_PrivateKey::public_key() const {
417 return std::make_unique<XMSS_PublicKey>(xmss_parameters().oid(), root(), public_seed());
418}
419
420std::unique_ptr<PK_Ops::Signature> XMSS_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
421 std::string_view /*params*/,
422 std::string_view provider) const {
423 if(provider == "base" || provider.empty()) {
424 return std::make_unique<XMSS_Signature_Operation>(*this);
425 }
426
427 throw Provider_Not_Found(algo_name(), provider);
428}
429
430} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:62
BER_Decoder & decode(bool &out)
Definition ber_dec.h:188
BER_Decoder & verify_end()
Definition ber_dec.cpp:217
secure_vector< uint8_t > get_contents()
Definition der_enc.cpp:134
DER_Encoder & encode(bool b)
Definition der_enc.cpp:252
void set_index_lower_bound(const KeyId &key_id, uint64_t min)
static Stateful_Key_Index_Registry & global()
uint64_t reserve_next_index(const KeyId &key_id)
uint64_t remaining_operations(const KeyId &key_id, uint64_t max)
size_t worker_count() const
Definition thread_pool.h:52
auto run(F &&f, Args &&... args) -> std::future< std::invoke_result_t< F, Args... > >
Definition thread_pool.h:66
static Thread_Pool & global_instance()
static void create_l_tree(secure_vector< uint8_t > &result, wots_keysig_t pk, XMSS_Address adrs, const secure_vector< uint8_t > &seed, XMSS_Hash &hash, const XMSS_Parameters &params)
static void randomize_tree_hash(secure_vector< uint8_t > &result, const secure_vector< uint8_t > &left, const secure_vector< uint8_t > &right, XMSS_Address adrs, const secure_vector< uint8_t > &seed, XMSS_Hash &hash, const XMSS_Parameters &params)
std::unique_ptr< Public_Key > public_key() const override
size_t remaining_signatures() const
size_t unused_leaf_index() const
std::optional< uint64_t > remaining_operations() const override
Retrieves the number of remaining operations if this is a stateful private key.
WOTS_Derivation_Method wots_derivation_method() const
secure_vector< uint8_t > raw_private_key() const
secure_vector< uint8_t > private_key_bits() const override
std::unique_ptr< PK_Ops::Signature > create_signature_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
XMSS_PrivateKey(XMSS_Parameters::xmss_algorithm_t xmss_algo_id, RandomNumberGenerator &rng, WOTS_Derivation_Method wots_derivation_method=WOTS_Derivation_Method::NIST_SP800_208)
const secure_vector< uint8_t > & root() const
Definition xmss.h:116
secure_vector< uint8_t > m_root
Definition xmss.h:124
const secure_vector< uint8_t > & public_seed() const
Definition xmss.h:114
secure_vector< uint8_t > m_public_seed
Definition xmss.h:125
const XMSS_Parameters & xmss_parameters() const
Definition xmss.h:118
XMSS_Parameters m_xmss_params
Definition xmss.h:122
std::vector< uint8_t > raw_public_key() const
XMSS_WOTS_Parameters m_wots_params
Definition xmss.h:123
std::string algo_name() const override
Definition xmss.h:70
XMSS_PublicKey(XMSS_Parameters::xmss_algorithm_t xmss_oid, RandomNumberGenerator &rng)
constexpr RT checked_cast_to(AT i)
Definition int_utils.h:74
constexpr auto concat(Rs &&... ranges)
Definition concat_util.h:90
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:68
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:745
WOTS_Derivation_Method
Definition xmss.h:136
constexpr auto load_be(ParamTs &&... params)
Definition loadstor.h:504