1 /*
2  *  The LMS stateful-hash public-key signature scheme
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 /*
9  *  The following sources were referenced in the design of this implementation
10  *  of the LMS algorithm:
11  *
12  *  [1] IETF RFC8554
13  *      D. McGrew, M. Curcio, S.Fluhrer
14  *      https://datatracker.ietf.org/doc/html/rfc8554
15  *
16  *  [2] NIST Special Publication 800-208
17  *      David A. Cooper et. al.
18  *      https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-208.pdf
19  */
20 
21 #include "common.h"
22 
23 #if defined(MBEDTLS_LMS_C)
24 
25 #include <string.h>
26 
27 #include "lmots.h"
28 
29 #include "psa/crypto.h"
30 #include "psa_util_internal.h"
31 #include "mbedtls/lms.h"
32 #include "mbedtls/error.h"
33 #include "mbedtls/platform_util.h"
34 
35 #include "mbedtls/platform.h"
36 
37 /* Define a local translating function to save code size by not using too many
38  * arguments in each translating place. */
local_err_translation(psa_status_t status)39 static int local_err_translation(psa_status_t status)
40 {
41     return psa_status_to_mbedtls(status, psa_to_lms_errors,
42                                  ARRAY_LENGTH(psa_to_lms_errors),
43                                  psa_generic_status_to_mbedtls);
44 }
45 #define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
46 
47 #define SIG_Q_LEAF_ID_OFFSET     (0)
48 #define SIG_OTS_SIG_OFFSET       (SIG_Q_LEAF_ID_OFFSET + \
49                                   MBEDTLS_LMOTS_Q_LEAF_ID_LEN)
50 #define SIG_TYPE_OFFSET(otstype) (SIG_OTS_SIG_OFFSET   + \
51                                   MBEDTLS_LMOTS_SIG_LEN(otstype))
52 #define SIG_PATH_OFFSET(otstype) (SIG_TYPE_OFFSET(otstype) + \
53                                   MBEDTLS_LMS_TYPE_LEN)
54 
55 #define PUBLIC_KEY_TYPE_OFFSET      (0)
56 #define PUBLIC_KEY_OTSTYPE_OFFSET   (PUBLIC_KEY_TYPE_OFFSET + \
57                                      MBEDTLS_LMS_TYPE_LEN)
58 #define PUBLIC_KEY_I_KEY_ID_OFFSET  (PUBLIC_KEY_OTSTYPE_OFFSET  + \
59                                      MBEDTLS_LMOTS_TYPE_LEN)
60 #define PUBLIC_KEY_ROOT_NODE_OFFSET (PUBLIC_KEY_I_KEY_ID_OFFSET + \
61                                      MBEDTLS_LMOTS_I_KEY_ID_LEN)
62 
63 
64 /* Currently only support H=10 */
65 #define H_TREE_HEIGHT_MAX                  10
66 #define MERKLE_TREE_NODE_AM(type)          ((size_t) 1 << (MBEDTLS_LMS_H_TREE_HEIGHT(type) + 1u))
67 #define MERKLE_TREE_LEAF_NODE_AM(type)     ((size_t) 1 << MBEDTLS_LMS_H_TREE_HEIGHT(type))
68 #define MERKLE_TREE_INTERNAL_NODE_AM(type) ((unsigned int) \
69                                             (1u << MBEDTLS_LMS_H_TREE_HEIGHT(type)))
70 
71 #define D_CONST_LEN           (2)
72 static const unsigned char D_LEAF_CONSTANT_BYTES[D_CONST_LEN] = { 0x82, 0x82 };
73 static const unsigned char D_INTR_CONSTANT_BYTES[D_CONST_LEN] = { 0x83, 0x83 };
74 
75 
76 /* Calculate the value of a leaf node of the Merkle tree (which is a hash of a
77  * public key and some other parameters like the leaf index). This function
78  * implements RFC8554 section 5.3, in the case where r >= 2^h.
79  *
80  *  params              The LMS parameter set, the underlying LMOTS
81  *                      parameter set, and I value which describe the key
82  *                      being used.
83  *
84  *  pub_key             The public key of the private whose index
85  *                      corresponds to the index of this leaf node. This
86  *                      is a hash output.
87  *
88  *  r_node_idx          The index of this node in the Merkle tree. Note
89  *                      that the root node of the Merkle tree is
90  *                      1-indexed.
91  *
92  *  out                 The output node value, which is a hash output.
93  */
create_merkle_leaf_value(const mbedtls_lms_parameters_t * params,unsigned char * pub_key,unsigned int r_node_idx,unsigned char * out)94 static int create_merkle_leaf_value(const mbedtls_lms_parameters_t *params,
95                                     unsigned char *pub_key,
96                                     unsigned int r_node_idx,
97                                     unsigned char *out)
98 {
99     psa_hash_operation_t op;
100     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
101     size_t output_hash_len;
102     unsigned char r_node_idx_bytes[4];
103 
104     op = psa_hash_operation_init();
105     status = psa_hash_setup(&op, PSA_ALG_SHA_256);
106     if (status != PSA_SUCCESS) {
107         goto exit;
108     }
109 
110     status = psa_hash_update(&op, params->I_key_identifier,
111                              MBEDTLS_LMOTS_I_KEY_ID_LEN);
112     if (status != PSA_SUCCESS) {
113         goto exit;
114     }
115 
116     MBEDTLS_PUT_UINT32_BE(r_node_idx, r_node_idx_bytes, 0);
117     status = psa_hash_update(&op, r_node_idx_bytes, 4);
118     if (status != PSA_SUCCESS) {
119         goto exit;
120     }
121 
122     status = psa_hash_update(&op, D_LEAF_CONSTANT_BYTES, D_CONST_LEN);
123     if (status != PSA_SUCCESS) {
124         goto exit;
125     }
126 
127     status = psa_hash_update(&op, pub_key,
128                              MBEDTLS_LMOTS_N_HASH_LEN(params->otstype));
129     if (status != PSA_SUCCESS) {
130         goto exit;
131     }
132 
133     status = psa_hash_finish(&op, out, MBEDTLS_LMS_M_NODE_BYTES(params->type),
134                              &output_hash_len);
135     if (status != PSA_SUCCESS) {
136         goto exit;
137     }
138 
139 exit:
140     psa_hash_abort(&op);
141 
142     return PSA_TO_MBEDTLS_ERR(status);
143 }
144 
145 /* Calculate the value of an internal node of the Merkle tree (which is a hash
146  * of a public key and some other parameters like the node index). This function
147  * implements RFC8554 section 5.3, in the case where r < 2^h.
148  *
149  *  params              The LMS parameter set, the underlying LMOTS
150  *                      parameter set, and I value which describe the key
151  *                      being used.
152  *
153  *  left_node           The value of the child of this node which is on
154  *                      the left-hand side. As with all nodes on the
155  *                      Merkle tree, this is a hash output.
156  *
157  *  right_node          The value of the child of this node which is on
158  *                      the right-hand side. As with all nodes on the
159  *                      Merkle tree, this is a hash output.
160  *
161  *  r_node_idx          The index of this node in the Merkle tree. Note
162  *                      that the root node of the Merkle tree is
163  *                      1-indexed.
164  *
165  *  out                 The output node value, which is a hash output.
166  */
create_merkle_internal_value(const mbedtls_lms_parameters_t * params,const unsigned char * left_node,const unsigned char * right_node,unsigned int r_node_idx,unsigned char * out)167 static int create_merkle_internal_value(const mbedtls_lms_parameters_t *params,
168                                         const unsigned char *left_node,
169                                         const unsigned char *right_node,
170                                         unsigned int r_node_idx,
171                                         unsigned char *out)
172 {
173     psa_hash_operation_t op;
174     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
175     size_t output_hash_len;
176     unsigned char r_node_idx_bytes[4];
177 
178     op = psa_hash_operation_init();
179     status = psa_hash_setup(&op, PSA_ALG_SHA_256);
180     if (status != PSA_SUCCESS) {
181         goto exit;
182     }
183 
184     status = psa_hash_update(&op, params->I_key_identifier,
185                              MBEDTLS_LMOTS_I_KEY_ID_LEN);
186     if (status != PSA_SUCCESS) {
187         goto exit;
188     }
189 
190     MBEDTLS_PUT_UINT32_BE(r_node_idx, r_node_idx_bytes, 0);
191     status = psa_hash_update(&op, r_node_idx_bytes, 4);
192     if (status != PSA_SUCCESS) {
193         goto exit;
194     }
195 
196     status = psa_hash_update(&op, D_INTR_CONSTANT_BYTES, D_CONST_LEN);
197     if (status != PSA_SUCCESS) {
198         goto exit;
199     }
200 
201     status = psa_hash_update(&op, left_node,
202                              MBEDTLS_LMS_M_NODE_BYTES(params->type));
203     if (status != PSA_SUCCESS) {
204         goto exit;
205     }
206 
207     status = psa_hash_update(&op, right_node,
208                              MBEDTLS_LMS_M_NODE_BYTES(params->type));
209     if (status != PSA_SUCCESS) {
210         goto exit;
211     }
212 
213     status = psa_hash_finish(&op, out, MBEDTLS_LMS_M_NODE_BYTES(params->type),
214                              &output_hash_len);
215     if (status != PSA_SUCCESS) {
216         goto exit;
217     }
218 
219 exit:
220     psa_hash_abort(&op);
221 
222     return PSA_TO_MBEDTLS_ERR(status);
223 }
224 
mbedtls_lms_public_init(mbedtls_lms_public_t * ctx)225 void mbedtls_lms_public_init(mbedtls_lms_public_t *ctx)
226 {
227     memset(ctx, 0, sizeof(*ctx));
228 }
229 
mbedtls_lms_public_free(mbedtls_lms_public_t * ctx)230 void mbedtls_lms_public_free(mbedtls_lms_public_t *ctx)
231 {
232     if (ctx == NULL) {
233         return;
234     }
235 
236     mbedtls_platform_zeroize(ctx, sizeof(*ctx));
237 }
238 
mbedtls_lms_import_public_key(mbedtls_lms_public_t * ctx,const unsigned char * key,size_t key_size)239 int mbedtls_lms_import_public_key(mbedtls_lms_public_t *ctx,
240                                   const unsigned char *key, size_t key_size)
241 {
242     mbedtls_lms_algorithm_type_t type;
243     mbedtls_lmots_algorithm_type_t otstype;
244 
245     type = (mbedtls_lms_algorithm_type_t) MBEDTLS_GET_UINT32_BE(key, PUBLIC_KEY_TYPE_OFFSET);
246     if (type != MBEDTLS_LMS_SHA256_M32_H10) {
247         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
248     }
249     ctx->params.type = type;
250 
251     if (key_size != MBEDTLS_LMS_PUBLIC_KEY_LEN(ctx->params.type)) {
252         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
253     }
254 
255     otstype = (mbedtls_lmots_algorithm_type_t)
256               MBEDTLS_GET_UINT32_BE(key, PUBLIC_KEY_OTSTYPE_OFFSET);
257     if (otstype != MBEDTLS_LMOTS_SHA256_N32_W8) {
258         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
259     }
260     ctx->params.otstype = otstype;
261 
262     memcpy(ctx->params.I_key_identifier,
263            key + PUBLIC_KEY_I_KEY_ID_OFFSET,
264            MBEDTLS_LMOTS_I_KEY_ID_LEN);
265     memcpy(ctx->T_1_pub_key, key + PUBLIC_KEY_ROOT_NODE_OFFSET,
266            MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type));
267 
268     ctx->have_public_key = 1;
269 
270     return 0;
271 }
272 
mbedtls_lms_export_public_key(const mbedtls_lms_public_t * ctx,unsigned char * key,size_t key_size,size_t * key_len)273 int mbedtls_lms_export_public_key(const mbedtls_lms_public_t *ctx,
274                                   unsigned char *key,
275                                   size_t key_size, size_t *key_len)
276 {
277     if (key_size < MBEDTLS_LMS_PUBLIC_KEY_LEN(ctx->params.type)) {
278         return MBEDTLS_ERR_LMS_BUFFER_TOO_SMALL;
279     }
280 
281     if (!ctx->have_public_key) {
282         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
283     }
284 
285     MBEDTLS_PUT_UINT32_BE(ctx->params.type, key, PUBLIC_KEY_TYPE_OFFSET);
286     MBEDTLS_PUT_UINT32_BE(ctx->params.otstype, key, PUBLIC_KEY_OTSTYPE_OFFSET);
287     memcpy(key + PUBLIC_KEY_I_KEY_ID_OFFSET,
288            ctx->params.I_key_identifier,
289            MBEDTLS_LMOTS_I_KEY_ID_LEN);
290     memcpy(key +PUBLIC_KEY_ROOT_NODE_OFFSET,
291            ctx->T_1_pub_key,
292            MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type));
293 
294     if (key_len != NULL) {
295         *key_len = MBEDTLS_LMS_PUBLIC_KEY_LEN(ctx->params.type);
296     }
297 
298     return 0;
299 }
300 
mbedtls_lms_verify(const mbedtls_lms_public_t * ctx,const unsigned char * msg,size_t msg_size,const unsigned char * sig,size_t sig_size)301 int mbedtls_lms_verify(const mbedtls_lms_public_t *ctx,
302                        const unsigned char *msg, size_t msg_size,
303                        const unsigned char *sig, size_t sig_size)
304 {
305     unsigned int q_leaf_identifier;
306     unsigned char Kc_candidate_ots_pub_key[MBEDTLS_LMOTS_N_HASH_LEN_MAX];
307     unsigned char Tc_candidate_root_node[MBEDTLS_LMS_M_NODE_BYTES_MAX];
308     unsigned int height;
309     unsigned int curr_node_id;
310     unsigned int parent_node_id;
311     const unsigned char *left_node;
312     const unsigned char *right_node;
313     mbedtls_lmots_parameters_t ots_params;
314     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
315 
316     if (!ctx->have_public_key) {
317         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
318     }
319 
320     if (ctx->params.type
321         != MBEDTLS_LMS_SHA256_M32_H10) {
322         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
323     }
324 
325     if (ctx->params.otstype
326         != MBEDTLS_LMOTS_SHA256_N32_W8) {
327         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
328     }
329 
330     if (sig_size != MBEDTLS_LMS_SIG_LEN(ctx->params.type, ctx->params.otstype)) {
331         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
332     }
333 
334     if (sig_size < SIG_OTS_SIG_OFFSET + MBEDTLS_LMOTS_TYPE_LEN) {
335         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
336     }
337 
338     if (MBEDTLS_GET_UINT32_BE(sig, SIG_OTS_SIG_OFFSET + MBEDTLS_LMOTS_SIG_TYPE_OFFSET)
339         != MBEDTLS_LMOTS_SHA256_N32_W8) {
340         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
341     }
342 
343     if (sig_size < SIG_TYPE_OFFSET(ctx->params.otstype) + MBEDTLS_LMS_TYPE_LEN) {
344         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
345     }
346 
347     if (MBEDTLS_GET_UINT32_BE(sig, SIG_TYPE_OFFSET(ctx->params.otstype))
348         != MBEDTLS_LMS_SHA256_M32_H10) {
349         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
350     }
351 
352 
353     q_leaf_identifier = MBEDTLS_GET_UINT32_BE(sig, SIG_Q_LEAF_ID_OFFSET);
354 
355     if (q_leaf_identifier >= MERKLE_TREE_LEAF_NODE_AM(ctx->params.type)) {
356         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
357     }
358 
359     memcpy(ots_params.I_key_identifier,
360            ctx->params.I_key_identifier,
361            MBEDTLS_LMOTS_I_KEY_ID_LEN);
362     MBEDTLS_PUT_UINT32_BE(q_leaf_identifier, ots_params.q_leaf_identifier, 0);
363     ots_params.type = ctx->params.otstype;
364 
365     ret = mbedtls_lmots_calculate_public_key_candidate(&ots_params,
366                                                        msg,
367                                                        msg_size,
368                                                        sig + SIG_OTS_SIG_OFFSET,
369                                                        MBEDTLS_LMOTS_SIG_LEN(ctx->params.otstype),
370                                                        Kc_candidate_ots_pub_key,
371                                                        sizeof(Kc_candidate_ots_pub_key),
372                                                        NULL);
373     if (ret != 0) {
374         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
375     }
376 
377     create_merkle_leaf_value(
378         &ctx->params,
379         Kc_candidate_ots_pub_key,
380         MERKLE_TREE_INTERNAL_NODE_AM(ctx->params.type) + q_leaf_identifier,
381         Tc_candidate_root_node);
382 
383     curr_node_id = MERKLE_TREE_INTERNAL_NODE_AM(ctx->params.type) +
384                    q_leaf_identifier;
385 
386     for (height = 0; height < MBEDTLS_LMS_H_TREE_HEIGHT(ctx->params.type);
387          height++) {
388         parent_node_id = curr_node_id / 2;
389 
390         /* Left/right node ordering matters for the hash */
391         if (curr_node_id & 1) {
392             left_node = sig + SIG_PATH_OFFSET(ctx->params.otstype) +
393                         height * MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type);
394             right_node = Tc_candidate_root_node;
395         } else {
396             left_node = Tc_candidate_root_node;
397             right_node = sig + SIG_PATH_OFFSET(ctx->params.otstype) +
398                          height * MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type);
399         }
400 
401         create_merkle_internal_value(&ctx->params, left_node, right_node,
402                                      parent_node_id, Tc_candidate_root_node);
403 
404         curr_node_id /= 2;
405     }
406 
407     if (memcmp(Tc_candidate_root_node, ctx->T_1_pub_key,
408                MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type))) {
409         return MBEDTLS_ERR_LMS_VERIFY_FAILED;
410     }
411 
412     return 0;
413 }
414 
415 #if defined(MBEDTLS_LMS_PRIVATE)
416 
417 /* Calculate a full Merkle tree based on a private key. This function
418  * implements RFC8554 section 5.3, and is used to generate a public key (as the
419  * public key is the root node of the Merkle tree).
420  *
421  *  ctx                 The LMS private context, containing a parameter
422  *                      set and private key material consisting of both
423  *                      public and private OTS.
424  *
425  *  tree                The output tree, which is 2^(H + 1) hash outputs.
426  *                      In the case of H=10 we have 2048 tree nodes (of
427  *                      which 1024 of them are leaf nodes). Note that
428  *                      because the Merkle tree root is 1-indexed, the 0
429  *                      index tree node is never used.
430  */
calculate_merkle_tree(const mbedtls_lms_private_t * ctx,unsigned char * tree)431 static int calculate_merkle_tree(const mbedtls_lms_private_t *ctx,
432                                  unsigned char *tree)
433 {
434     unsigned int priv_key_idx;
435     unsigned int r_node_idx;
436     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
437 
438     /* First create the leaf nodes, in ascending order */
439     for (priv_key_idx = 0;
440          priv_key_idx < MERKLE_TREE_INTERNAL_NODE_AM(ctx->params.type);
441          priv_key_idx++) {
442         r_node_idx = MERKLE_TREE_INTERNAL_NODE_AM(ctx->params.type) + priv_key_idx;
443 
444         ret = create_merkle_leaf_value(&ctx->params,
445                                        ctx->ots_public_keys[priv_key_idx].public_key,
446                                        r_node_idx,
447                                        &tree[r_node_idx * MBEDTLS_LMS_M_NODE_BYTES(
448                                                  ctx->params.type)]);
449         if (ret != 0) {
450             return ret;
451         }
452     }
453 
454     /* Then the internal nodes, in reverse order so that we can guarantee the
455      * parent has been created */
456     for (r_node_idx = MERKLE_TREE_INTERNAL_NODE_AM(ctx->params.type) - 1;
457          r_node_idx > 0;
458          r_node_idx--) {
459         ret = create_merkle_internal_value(&ctx->params,
460                                            &tree[(r_node_idx * 2) *
461                                                  MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type)],
462                                            &tree[(r_node_idx * 2 + 1) *
463                                                  MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type)],
464                                            r_node_idx,
465                                            &tree[r_node_idx *
466                                                  MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type)]);
467         if (ret != 0) {
468             return ret;
469         }
470     }
471 
472     return 0;
473 }
474 
475 /* Calculate a path from a leaf node of the Merkle tree to the root of the tree,
476  * and return the full path. This function implements RFC8554 section 5.4.1, as
477  * the Merkle path is the main component of an LMS signature.
478  *
479  *  ctx                 The LMS private context, containing a parameter
480  *                      set and private key material consisting of both
481  *                      public and private OTS.
482  *
483  *  leaf_node_id        Which leaf node to calculate the path from.
484  *
485  *  path                The output path, which is H hash outputs.
486  */
get_merkle_path(mbedtls_lms_private_t * ctx,unsigned int leaf_node_id,unsigned char * path)487 static int get_merkle_path(mbedtls_lms_private_t *ctx,
488                            unsigned int leaf_node_id,
489                            unsigned char *path)
490 {
491     const size_t node_bytes = MBEDTLS_LMS_M_NODE_BYTES(ctx->params.type);
492     unsigned int curr_node_id = leaf_node_id;
493     unsigned int adjacent_node_id;
494     unsigned char *tree = NULL;
495     unsigned int height;
496     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
497 
498     tree = mbedtls_calloc((size_t) MERKLE_TREE_NODE_AM(ctx->params.type),
499                           node_bytes);
500     if (tree == NULL) {
501         return MBEDTLS_ERR_LMS_ALLOC_FAILED;
502     }
503 
504     ret = calculate_merkle_tree(ctx, tree);
505     if (ret != 0) {
506         goto exit;
507     }
508 
509     for (height = 0; height < MBEDTLS_LMS_H_TREE_HEIGHT(ctx->params.type);
510          height++) {
511         adjacent_node_id = curr_node_id ^ 1;
512 
513         memcpy(&path[height * node_bytes],
514                &tree[adjacent_node_id * node_bytes], node_bytes);
515 
516         curr_node_id >>= 1;
517     }
518 
519     ret = 0;
520 
521 exit:
522     mbedtls_zeroize_and_free(tree, node_bytes *
523                              (size_t) MERKLE_TREE_NODE_AM(ctx->params.type));
524 
525     return ret;
526 }
527 
mbedtls_lms_private_init(mbedtls_lms_private_t * ctx)528 void mbedtls_lms_private_init(mbedtls_lms_private_t *ctx)
529 {
530     memset(ctx, 0, sizeof(*ctx));
531 }
532 
mbedtls_lms_private_free(mbedtls_lms_private_t * ctx)533 void mbedtls_lms_private_free(mbedtls_lms_private_t *ctx)
534 {
535     if (ctx == NULL) {
536         return;
537     }
538 
539     unsigned int idx;
540 
541     if (ctx->have_private_key) {
542         if (ctx->ots_private_keys != NULL) {
543             for (idx = 0; idx < MERKLE_TREE_LEAF_NODE_AM(ctx->params.type); idx++) {
544                 mbedtls_lmots_private_free(&ctx->ots_private_keys[idx]);
545             }
546         }
547 
548         if (ctx->ots_public_keys != NULL) {
549             for (idx = 0; idx < MERKLE_TREE_LEAF_NODE_AM(ctx->params.type); idx++) {
550                 mbedtls_lmots_public_free(&ctx->ots_public_keys[idx]);
551             }
552         }
553 
554         mbedtls_free(ctx->ots_private_keys);
555         mbedtls_free(ctx->ots_public_keys);
556     }
557 
558     mbedtls_platform_zeroize(ctx, sizeof(*ctx));
559 }
560 
561 
mbedtls_lms_generate_private_key(mbedtls_lms_private_t * ctx,mbedtls_lms_algorithm_type_t type,mbedtls_lmots_algorithm_type_t otstype,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,const unsigned char * seed,size_t seed_size)562 int mbedtls_lms_generate_private_key(mbedtls_lms_private_t *ctx,
563                                      mbedtls_lms_algorithm_type_t type,
564                                      mbedtls_lmots_algorithm_type_t otstype,
565                                      int (*f_rng)(void *, unsigned char *, size_t),
566                                      void *p_rng, const unsigned char *seed,
567                                      size_t seed_size)
568 {
569     unsigned int idx = 0;
570     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
571 
572     if (type != MBEDTLS_LMS_SHA256_M32_H10) {
573         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
574     }
575 
576     if (otstype != MBEDTLS_LMOTS_SHA256_N32_W8) {
577         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
578     }
579 
580     if (ctx->have_private_key) {
581         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
582     }
583 
584     ctx->params.type = type;
585     ctx->params.otstype = otstype;
586     ctx->have_private_key = 1;
587 
588     ret = f_rng(p_rng,
589                 ctx->params.I_key_identifier,
590                 MBEDTLS_LMOTS_I_KEY_ID_LEN);
591     if (ret != 0) {
592         goto exit;
593     }
594 
595     /* Requires a cast to size_t to avoid an implicit cast warning on certain
596      * platforms (particularly Windows) */
597     ctx->ots_private_keys = mbedtls_calloc((size_t) MERKLE_TREE_LEAF_NODE_AM(ctx->params.type),
598                                            sizeof(*ctx->ots_private_keys));
599     if (ctx->ots_private_keys == NULL) {
600         ret = MBEDTLS_ERR_LMS_ALLOC_FAILED;
601         goto exit;
602     }
603 
604     /* Requires a cast to size_t to avoid an implicit cast warning on certain
605      * platforms (particularly Windows) */
606     ctx->ots_public_keys = mbedtls_calloc((size_t) MERKLE_TREE_LEAF_NODE_AM(ctx->params.type),
607                                           sizeof(*ctx->ots_public_keys));
608     if (ctx->ots_public_keys == NULL) {
609         ret = MBEDTLS_ERR_LMS_ALLOC_FAILED;
610         goto exit;
611     }
612 
613     for (idx = 0; idx < MERKLE_TREE_LEAF_NODE_AM(ctx->params.type); idx++) {
614         mbedtls_lmots_private_init(&ctx->ots_private_keys[idx]);
615         mbedtls_lmots_public_init(&ctx->ots_public_keys[idx]);
616     }
617 
618 
619     for (idx = 0; idx < MERKLE_TREE_LEAF_NODE_AM(ctx->params.type); idx++) {
620         ret = mbedtls_lmots_generate_private_key(&ctx->ots_private_keys[idx],
621                                                  otstype,
622                                                  ctx->params.I_key_identifier,
623                                                  idx, seed, seed_size);
624         if (ret != 0) {
625             goto exit;
626         }
627 
628         ret = mbedtls_lmots_calculate_public_key(&ctx->ots_public_keys[idx],
629                                                  &ctx->ots_private_keys[idx]);
630         if (ret != 0) {
631             goto exit;
632         }
633     }
634 
635     ctx->q_next_usable_key = 0;
636 
637 exit:
638     if (ret != 0) {
639         mbedtls_lms_private_free(ctx);
640     }
641 
642     return ret;
643 }
644 
mbedtls_lms_calculate_public_key(mbedtls_lms_public_t * ctx,const mbedtls_lms_private_t * priv_ctx)645 int mbedtls_lms_calculate_public_key(mbedtls_lms_public_t *ctx,
646                                      const mbedtls_lms_private_t *priv_ctx)
647 {
648     const size_t node_bytes = MBEDTLS_LMS_M_NODE_BYTES(priv_ctx->params.type);
649     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
650     unsigned char *tree = NULL;
651 
652     if (!priv_ctx->have_private_key) {
653         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
654     }
655 
656     if (priv_ctx->params.type
657         != MBEDTLS_LMS_SHA256_M32_H10) {
658         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
659     }
660 
661     if (priv_ctx->params.otstype
662         != MBEDTLS_LMOTS_SHA256_N32_W8) {
663         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
664     }
665 
666     tree = mbedtls_calloc((size_t) MERKLE_TREE_NODE_AM(priv_ctx->params.type),
667                           node_bytes);
668     if (tree == NULL) {
669         return MBEDTLS_ERR_LMS_ALLOC_FAILED;
670     }
671 
672     memcpy(&ctx->params, &priv_ctx->params,
673            sizeof(mbedtls_lmots_parameters_t));
674 
675     ret = calculate_merkle_tree(priv_ctx, tree);
676     if (ret != 0) {
677         goto exit;
678     }
679 
680     /* Root node is always at position 1, due to 1-based indexing */
681     memcpy(ctx->T_1_pub_key, &tree[node_bytes], node_bytes);
682 
683     ctx->have_public_key = 1;
684 
685     ret = 0;
686 
687 exit:
688     mbedtls_zeroize_and_free(tree, node_bytes *
689                              (size_t) MERKLE_TREE_NODE_AM(priv_ctx->params.type));
690 
691     return ret;
692 }
693 
694 
mbedtls_lms_sign(mbedtls_lms_private_t * ctx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,const unsigned char * msg,unsigned int msg_size,unsigned char * sig,size_t sig_size,size_t * sig_len)695 int mbedtls_lms_sign(mbedtls_lms_private_t *ctx,
696                      int (*f_rng)(void *, unsigned char *, size_t),
697                      void *p_rng, const unsigned char *msg,
698                      unsigned int msg_size, unsigned char *sig, size_t sig_size,
699                      size_t *sig_len)
700 {
701     uint32_t q_leaf_identifier;
702     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
703 
704     if (!ctx->have_private_key) {
705         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
706     }
707 
708     if (sig_size < MBEDTLS_LMS_SIG_LEN(ctx->params.type, ctx->params.otstype)) {
709         return MBEDTLS_ERR_LMS_BUFFER_TOO_SMALL;
710     }
711 
712     if (ctx->params.type != MBEDTLS_LMS_SHA256_M32_H10) {
713         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
714     }
715 
716     if (ctx->params.otstype
717         != MBEDTLS_LMOTS_SHA256_N32_W8) {
718         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
719     }
720 
721     if (ctx->q_next_usable_key >= MERKLE_TREE_LEAF_NODE_AM(ctx->params.type)) {
722         return MBEDTLS_ERR_LMS_OUT_OF_PRIVATE_KEYS;
723     }
724 
725 
726     q_leaf_identifier = ctx->q_next_usable_key;
727     /* This new value must _always_ be written back to the disk before the
728      * signature is returned.
729      */
730     ctx->q_next_usable_key += 1;
731 
732     if (MBEDTLS_LMS_SIG_LEN(ctx->params.type, ctx->params.otstype)
733         < SIG_OTS_SIG_OFFSET) {
734         return MBEDTLS_ERR_LMS_BAD_INPUT_DATA;
735     }
736 
737     ret = mbedtls_lmots_sign(&ctx->ots_private_keys[q_leaf_identifier],
738                              f_rng,
739                              p_rng,
740                              msg,
741                              msg_size,
742                              sig + SIG_OTS_SIG_OFFSET,
743                              MBEDTLS_LMS_SIG_LEN(ctx->params.type,
744                                                  ctx->params.otstype) - SIG_OTS_SIG_OFFSET,
745                              NULL);
746     if (ret != 0) {
747         return ret;
748     }
749 
750     MBEDTLS_PUT_UINT32_BE(ctx->params.type, sig, SIG_TYPE_OFFSET(ctx->params.otstype));
751     MBEDTLS_PUT_UINT32_BE(q_leaf_identifier, sig, SIG_Q_LEAF_ID_OFFSET);
752 
753     ret = get_merkle_path(ctx,
754                           MERKLE_TREE_INTERNAL_NODE_AM(ctx->params.type) + q_leaf_identifier,
755                           sig + SIG_PATH_OFFSET(ctx->params.otstype));
756     if (ret != 0) {
757         return ret;
758     }
759 
760     if (sig_len != NULL) {
761         *sig_len = MBEDTLS_LMS_SIG_LEN(ctx->params.type, ctx->params.otstype);
762     }
763 
764 
765     return 0;
766 }
767 
768 #endif /* defined(MBEDTLS_LMS_PRIVATE) */
769 #endif /* defined(MBEDTLS_LMS_C) */
770