Botan 3.9.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 Siganture 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 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/internal/loadstor.h>
24#include <botan/internal/stl_util.h>
25#include <botan/internal/xmss_common_ops.h>
26#include <botan/internal/xmss_index_registry.h>
27#include <botan/internal/xmss_signature_operation.h>
28#include <iterator>
29
30#if defined(BOTAN_HAS_THREAD_UTILS)
31 #include <botan/internal/thread_pool.h>
32#endif
33
34namespace Botan {
35
36namespace {
37
38// fall back to raw decoding for previous versions, which did not encode an OCTET STRING
39secure_vector<uint8_t> extract_raw_private_key(std::span<const uint8_t> key_bits, const XMSS_Parameters& xmss_params) {
41
42 // The public part of the input key bits was already parsed, so we can
43 // decide depending on the buffer length whether this must be BER decoded.
44 if(key_bits.size() == xmss_params.raw_private_key_size() ||
45 key_bits.size() == xmss_params.raw_legacy_private_key_size()) {
46 raw_key.assign(key_bits.begin(), key_bits.end());
47 } else {
48 DataSource_Memory src(key_bits);
50 }
51
52 return raw_key;
53}
54
55} // namespace
56
57class XMSS_PrivateKey_Internal {
58 public:
59 XMSS_PrivateKey_Internal(const XMSS_Parameters& xmss_params,
60 const XMSS_WOTS_Parameters& wots_params,
61 WOTS_Derivation_Method wots_derivation_method,
62 RandomNumberGenerator& rng) :
63 m_xmss_params(xmss_params),
64 m_wots_params(wots_params),
65 m_wots_derivation_method(wots_derivation_method),
66 m_hash(xmss_params),
67 m_prf(rng.random_vec(xmss_params.element_size())),
68 m_private_seed(rng.random_vec(xmss_params.element_size())),
69 m_index_reg(XMSS_Index_Registry::get_instance()) {}
70
71 XMSS_PrivateKey_Internal(const XMSS_Parameters& xmss_params,
72 const XMSS_WOTS_Parameters& wots_params,
73 WOTS_Derivation_Method wots_derivation_method,
74 secure_vector<uint8_t> private_seed,
76 m_xmss_params(xmss_params),
77 m_wots_params(wots_params),
78 m_wots_derivation_method(wots_derivation_method),
79 m_hash(m_xmss_params),
80 m_prf(std::move(prf)),
81 m_private_seed(std::move(private_seed)),
82 m_index_reg(XMSS_Index_Registry::get_instance()) {}
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),
88 m_wots_params(wots_params),
89 m_hash(m_xmss_params),
90 m_index_reg(XMSS_Index_Registry::get_instance()) {
91 /*
92 The code requires sizeof(size_t) >= ceil(tree_height / 8)
93
94 Maximum supported tree height is 20, ceil(20/8) == 3, so 4 byte
95 size_t is sufficient for all defined parameters, or even a
96 (hypothetical) tree height 32, which would be extremely slow to
97 compute.
98 */
99 static_assert(sizeof(size_t) >= 4, "size_t is big enough to support leaf index");
100
101 const secure_vector<uint8_t> raw_key = extract_raw_private_key(key_bits, xmss_params);
102
103 if(raw_key.size() != m_xmss_params.raw_private_key_size() &&
104 raw_key.size() != m_xmss_params.raw_legacy_private_key_size()) {
105 throw Decoding_Error("Invalid XMSS private key size");
106 }
107
108 BufferSlicer s(raw_key);
109
110 // We're not interested in the public key here
111 s.skip(m_xmss_params.raw_public_key_size());
112
113 auto unused_leaf_bytes = s.take(sizeof(uint32_t));
114 size_t unused_leaf = load_be<uint32_t>(unused_leaf_bytes.data(), 0);
115 if(unused_leaf >= (1ULL << m_xmss_params.tree_height())) {
116 throw Decoding_Error("XMSS private key leaf index out of bounds");
117 }
118
119 m_prf = s.copy_as_secure_vector(m_xmss_params.element_size());
120 m_private_seed = s.copy_as_secure_vector(m_xmss_params.element_size());
121 set_unused_leaf_index(unused_leaf);
122
123 // Legacy keys generated prior to Botan 3.x don't feature a
124 // WOTS+ key derivation method encoded in their private key.
125 m_wots_derivation_method =
126 (s.empty()) ? WOTS_Derivation_Method::Botan2x : static_cast<WOTS_Derivation_Method>(s.take(1).front());
127
128 BOTAN_ASSERT_NOMSG(s.empty());
129 }
130
131 secure_vector<uint8_t> serialize(std::vector<uint8_t> raw_public_key) const {
132 std::vector<uint8_t> unused_index(4);
133 store_be(static_cast<uint32_t>(unused_leaf_index()), unused_index.data());
134
135 std::vector<uint8_t> wots_derivation_method;
136 wots_derivation_method.push_back(static_cast<uint8_t>(m_wots_derivation_method));
137
139 raw_public_key, unused_index, m_prf, m_private_seed, wots_derivation_method);
140 }
141
142 XMSS_Hash& hash() { return m_hash; }
143
144 const secure_vector<uint8_t>& prf_value() const { return m_prf; }
145
146 const secure_vector<uint8_t>& private_seed() { return m_private_seed; }
147
148 const XMSS_WOTS_Parameters& wots_parameters() { return m_wots_params; }
149
150 WOTS_Derivation_Method wots_derivation_method() const { return m_wots_derivation_method; }
151
152 XMSS_Index_Registry& index_registry() { return m_index_reg; }
153
154 std::shared_ptr<Atomic<size_t>> recover_global_leaf_index() const {
156 m_private_seed.size() == m_xmss_params.element_size() && m_prf.size() == m_xmss_params.element_size(),
157 "Trying to retrieve index for partially initialized key");
158 return m_index_reg.get(m_private_seed, m_prf);
159 }
160
161 void set_unused_leaf_index(size_t idx) {
162 if(idx >= (1ULL << m_xmss_params.tree_height())) {
163 throw Decoding_Error("XMSS private key leaf index out of bounds");
164 } else {
165 std::atomic<size_t>& index = static_cast<std::atomic<size_t>&>(*recover_global_leaf_index());
166 size_t current = 0;
167
168 // NOLINTNEXTLINE(*-avoid-do-while)
169 do {
170 current = index.load();
171 if(current > idx) {
172 return;
173 }
174 } while(!index.compare_exchange_strong(current, idx));
175 }
176 }
177
178 size_t reserve_unused_leaf_index() {
179 size_t idx = (static_cast<std::atomic<size_t>&>(*recover_global_leaf_index())).fetch_add(1);
180 if(idx >= m_xmss_params.total_number_of_signatures()) {
181 throw Decoding_Error("XMSS private key, one time signatures exhaused");
182 }
183 return idx;
184 }
185
186 size_t unused_leaf_index() const { return *recover_global_leaf_index(); }
187
188 size_t remaining_signatures() const {
189 return m_xmss_params.total_number_of_signatures() - *recover_global_leaf_index();
190 }
191
192 private:
193 XMSS_Parameters m_xmss_params;
194 XMSS_WOTS_Parameters m_wots_params;
195 WOTS_Derivation_Method m_wots_derivation_method;
196
197 XMSS_Hash m_hash;
199 secure_vector<uint8_t> m_private_seed;
200 XMSS_Index_Registry& m_index_reg;
201};
202
203XMSS_PrivateKey::XMSS_PrivateKey(std::span<const uint8_t> key_bits) :
204 XMSS_PublicKey(key_bits),
205 m_private(std::make_shared<XMSS_PrivateKey_Internal>(m_xmss_params, m_wots_params, key_bits)) {}
206
210 XMSS_PublicKey(xmss_algo_id, rng),
211 m_private(std::make_shared<XMSS_PrivateKey_Internal>(m_xmss_params, m_wots_params, wots_derivation_method, rng)) {
212 XMSS_Address adrs;
213 m_root = tree_hash(0, XMSS_PublicKey::m_xmss_params.tree_height(), adrs);
214}
215
217 size_t idx_leaf,
218 secure_vector<uint8_t> wots_priv_seed,
223 XMSS_PublicKey(xmss_algo_id, std::move(root), std::move(public_seed)),
224 m_private(std::make_shared<XMSS_PrivateKey_Internal>(
225 m_xmss_params, m_wots_params, wots_derivation_method, std::move(wots_priv_seed), std::move(prf))) {
226 m_private->set_unused_leaf_index(idx_leaf);
227 BOTAN_ARG_CHECK(m_private->prf_value().size() == m_xmss_params.element_size(),
228 "XMSS: unexpected byte length of PRF value");
229 BOTAN_ARG_CHECK(m_private->private_seed().size() == m_xmss_params.element_size(),
230 "XMSS: unexpected byte length of private seed");
231}
232
233secure_vector<uint8_t> XMSS_PrivateKey::tree_hash(size_t start_idx, size_t target_node_height, XMSS_Address& adrs) {
234 BOTAN_ASSERT_NOMSG(target_node_height <= 30);
235 BOTAN_ASSERT((start_idx % (static_cast<size_t>(1) << target_node_height)) == 0,
236 "Start index must be divisible by 2^{target node height}.");
237
238#if defined(BOTAN_HAS_THREAD_UTILS)
239 // dertermine number of parallel tasks to split the tree_hashing into.
240
242
243 const size_t split_level = std::min(target_node_height, thread_pool.worker_count());
244
245 // skip parallelization overhead for leaf nodes.
246 if(split_level == 0) {
248 tree_hash_subtree(result, start_idx, target_node_height, adrs);
249 return result;
250 }
251
252 const size_t subtrees = static_cast<size_t>(1) << split_level;
253 const size_t last_idx = (static_cast<size_t>(1) << (target_node_height)) + start_idx;
254 const size_t offs = (last_idx - start_idx) / subtrees;
255 // this cast cannot overflow because target_node_height is limited
256 uint8_t level = static_cast<uint8_t>(split_level); // current level in the tree
257
258 BOTAN_ASSERT((last_idx - start_idx) % subtrees == 0,
259 "Number of worker threads in tree_hash need to divide range "
260 "of calculated nodes.");
261
262 std::vector<secure_vector<uint8_t>> nodes(subtrees,
264 std::vector<XMSS_Address> node_addresses(subtrees, adrs);
265 std::vector<XMSS_Hash> xmss_hash(subtrees, m_private->hash());
266 std::vector<std::future<void>> work;
267
268 // Calculate multiple subtrees in parallel.
269 for(size_t i = 0; i < subtrees; i++) {
270 using tree_hash_subtree_fn_t =
271 void (XMSS_PrivateKey::*)(secure_vector<uint8_t>&, size_t, size_t, XMSS_Address&, XMSS_Hash&);
272
273 tree_hash_subtree_fn_t work_fn = &XMSS_PrivateKey::tree_hash_subtree;
274
275 work.push_back(thread_pool.run(work_fn,
276 this,
277 std::ref(nodes[i]),
278 start_idx + i * offs,
279 target_node_height - split_level,
280 std::ref(node_addresses[i]),
281 std::ref(xmss_hash[i])));
282 }
283
284 for(auto& w : work) {
285 w.get();
286 }
287 work.clear();
288
289 // Parallelize the top tree levels horizontally
290 while(level-- > 1) {
291 std::vector<secure_vector<uint8_t>> ro_nodes(nodes.begin(),
292 nodes.begin() + (static_cast<size_t>(1) << (level + 1)));
293
294 for(size_t i = 0; i < (static_cast<size_t>(1) << level); i++) {
295 BOTAN_ASSERT_NOMSG(xmss_hash.size() > i);
296
297 node_addresses[i].set_tree_height(static_cast<uint32_t>(target_node_height - (level + 1)));
298 node_addresses[i].set_tree_index((node_addresses[2 * i + 1].get_tree_index() - 1) >> 1);
299
300 work.push_back(thread_pool.run(&XMSS_Common_Ops::randomize_tree_hash,
301 std::ref(nodes[i]),
302 std::cref(ro_nodes[2 * i]),
303 std::cref(ro_nodes[2 * i + 1]),
304 std::ref(node_addresses[i]),
305 std::cref(this->public_seed()),
306 std::ref(xmss_hash[i]),
307 std::cref(m_xmss_params)));
308 }
309
310 for(auto& w : work) {
311 w.get();
312 }
313 work.clear();
314 }
315
316 // Avoid creation an extra thread to calculate root node.
317 node_addresses[0].set_tree_height(static_cast<uint32_t>(target_node_height - 1));
318 node_addresses[0].set_tree_index((node_addresses[1].get_tree_index() - 1) >> 1);
320 nodes[0], nodes[0], nodes[1], node_addresses[0], this->public_seed(), m_private->hash(), m_xmss_params);
321 return nodes[0];
322#else
324 tree_hash_subtree(result, start_idx, target_node_height, adrs, m_private->hash());
325 return result;
326#endif
327}
328
329void XMSS_PrivateKey::tree_hash_subtree(secure_vector<uint8_t>& result,
330 size_t start_idx,
331 size_t target_node_height,
332 XMSS_Address& adrs) {
333 return tree_hash_subtree(result, start_idx, target_node_height, adrs, m_private->hash());
334}
335
336void XMSS_PrivateKey::tree_hash_subtree(
337 secure_vector<uint8_t>& result, size_t start_idx, size_t target_node_height, XMSS_Address& adrs, XMSS_Hash& hash) {
338 const secure_vector<uint8_t>& seed = this->public_seed();
339
340 std::vector<secure_vector<uint8_t>> nodes(target_node_height + 1,
342
343 // node stack, holds all nodes on stack and one extra "pending" node. This
344 // temporary node referred to as "node" in the XMSS standard document stays
345 // a pending element, meaning it is not regarded as element on the stack
346 // until level is increased.
347 std::vector<uint8_t> node_levels(target_node_height + 1);
348
349 uint8_t level = 0; // current level on the node stack.
350 const size_t last_idx = (static_cast<size_t>(1) << target_node_height) + start_idx;
351
352 for(size_t i = start_idx; i < last_idx; i++) {
354 adrs.set_ots_address(static_cast<uint32_t>(i));
355
356 XMSS_WOTS_PublicKey pk = this->wots_public_key_for(adrs, hash);
357
359 adrs.set_ltree_address(static_cast<uint32_t>(i));
360 XMSS_Common_Ops::create_l_tree(nodes[level], pk.key_data(), adrs, seed, hash, m_xmss_params);
361 node_levels[level] = 0;
362
364 adrs.set_tree_height(0);
365 adrs.set_tree_index(static_cast<uint32_t>(i));
366
367 while(level > 0 && node_levels[level] == node_levels[level - 1]) {
368 adrs.set_tree_index(((adrs.get_tree_index() - 1) >> 1));
370 nodes[level - 1], nodes[level - 1], nodes[level], adrs, seed, hash, m_xmss_params);
371 node_levels[level - 1]++;
372 level--; //Pop stack top element
373 adrs.set_tree_height(adrs.get_tree_height() + 1);
374 }
375 level++; //push temporary node to stack
376 }
377 result = nodes[level - 1];
378}
379
380XMSS_WOTS_PublicKey XMSS_PrivateKey::wots_public_key_for(XMSS_Address& adrs, XMSS_Hash& hash) const {
381 const auto private_key = wots_private_key_for(adrs, hash);
382 return XMSS_WOTS_PublicKey(m_private->wots_parameters(), m_public_seed, private_key, adrs, hash);
383}
384
385XMSS_WOTS_PrivateKey XMSS_PrivateKey::wots_private_key_for(XMSS_Address& adrs, XMSS_Hash& hash) const {
386 switch(wots_derivation_method()) {
388 return XMSS_WOTS_PrivateKey(
389 m_private->wots_parameters(), m_public_seed, m_private->private_seed(), adrs, hash);
391 return XMSS_WOTS_PrivateKey(m_private->wots_parameters(), m_private->private_seed(), adrs, hash);
392 }
393
394 throw Invalid_State("WOTS derivation method is out of the enum's range");
395}
396
400
401size_t XMSS_PrivateKey::reserve_unused_leaf_index() {
402 return m_private->reserve_unused_leaf_index();
403}
404
406 return m_private->unused_leaf_index();
407}
408
410 return m_private->remaining_signatures();
411}
412
413std::optional<uint64_t> XMSS_PrivateKey::remaining_operations() const {
414 return m_private->remaining_signatures();
415}
416
417const secure_vector<uint8_t>& XMSS_PrivateKey::prf_value() const {
418 return m_private->prf_value();
419}
420
422 return m_private->serialize(raw_public_key());
423}
424
426 return m_private->wots_derivation_method();
427}
428
429std::unique_ptr<Public_Key> XMSS_PrivateKey::public_key() const {
430 return std::make_unique<XMSS_PublicKey>(xmss_parameters().oid(), root(), public_seed());
431}
432
433std::unique_ptr<PK_Ops::Signature> XMSS_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
434 std::string_view /*params*/,
435 std::string_view provider) const {
436 if(provider == "base" || provider.empty()) {
437 return std::make_unique<XMSS_Signature_Operation>(*this);
438 }
439
440 throw Provider_Not_Found(algo_name(), provider);
441}
442
443} // 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:214
secure_vector< uint8_t > get_contents()
Definition der_enc.cpp:134
DER_Encoder & encode(bool b)
Definition der_enc.cpp:252
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:118
secure_vector< uint8_t > m_root
Definition xmss.h:126
const secure_vector< uint8_t > & public_seed() const
Definition xmss.h:116
secure_vector< uint8_t > m_public_seed
Definition xmss.h:127
const XMSS_Parameters & xmss_parameters() const
Definition xmss.h:120
XMSS_Parameters m_xmss_params
Definition xmss.h:124
std::vector< uint8_t > raw_public_key() const
XMSS_WOTS_Parameters m_wots_params
Definition xmss.h:125
std::string algo_name() const override
Definition xmss.h:72
XMSS_PublicKey(XMSS_Parameters::xmss_algorithm_t xmss_oid, RandomNumberGenerator &rng)
constexpr auto concat(Rs &&... ranges)
Definition stl_util.h:255
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:69
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:745
WOTS_Derivation_Method
Definition xmss.h:138
constexpr auto load_be(ParamTs &&... params)
Definition loadstor.h:504