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