xref: /freebsd/crypto/openssl/crypto/ml_dsa/ml_dsa_key.c (revision 046c625e9382e17da953767b881aaa782fa73af8)
1 /*
2  * Copyright 2024-2025 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <openssl/core_dispatch.h>
11 #include <openssl/core_names.h>
12 #include <openssl/err.h>
13 #include <openssl/params.h>
14 #include <openssl/proverr.h>
15 #include <openssl/rand.h>
16 #include "ml_dsa_key.h"
17 #include "ml_dsa_matrix.h"
18 #include "ml_dsa_hash.h"
19 #include "internal/encoder.h"
20 
ossl_ml_dsa_key_params(const ML_DSA_KEY * key)21 const ML_DSA_PARAMS *ossl_ml_dsa_key_params(const ML_DSA_KEY *key)
22 {
23     return key->params;
24 }
25 
26 /* Returns the seed data or NULL if there is no seed */
ossl_ml_dsa_key_get_seed(const ML_DSA_KEY * key)27 const uint8_t *ossl_ml_dsa_key_get_seed(const ML_DSA_KEY *key)
28 {
29     return key->seed;
30 }
31 
ossl_ml_dsa_key_get_prov_flags(const ML_DSA_KEY * key)32 int ossl_ml_dsa_key_get_prov_flags(const ML_DSA_KEY *key)
33 {
34     return key->prov_flags;
35 }
36 
ossl_ml_dsa_set_prekey(ML_DSA_KEY * key,int flags_set,int flags_clr,const uint8_t * seed,size_t seed_len,const uint8_t * sk,size_t sk_len)37 int ossl_ml_dsa_set_prekey(ML_DSA_KEY *key, int flags_set, int flags_clr,
38                            const uint8_t *seed, size_t seed_len,
39                            const uint8_t *sk, size_t sk_len)
40 {
41     int ret = 0;
42 
43     if (key == NULL
44         || key->pub_encoding != NULL
45         || key->priv_encoding != NULL
46         || (sk != NULL && sk_len != key->params->sk_len)
47         || (seed != NULL && seed_len != ML_DSA_SEED_BYTES)
48         || key->seed != NULL)
49         return 0;
50 
51     if (sk != NULL
52         && (key->priv_encoding = OPENSSL_memdup(sk, sk_len)) == NULL)
53         goto end;
54     if (seed != NULL
55         && (key->seed = OPENSSL_memdup(seed, seed_len)) == NULL)
56         goto end;
57     key->prov_flags |= flags_set;
58     key->prov_flags &= ~flags_clr;
59     ret = 1;
60 
61  end:
62     if (!ret) {
63         OPENSSL_free(key->priv_encoding);
64         OPENSSL_free(key->seed);
65         key->priv_encoding = key->seed = NULL;
66     }
67     return ret;
68 }
69 
70 /**
71  * @brief Create a new ML_DSA_KEY object
72  *
73  * @param libctx A OSSL_LIB_CTX object used for fetching algorithms.
74  * @param propq The property query used for fetching algorithms
75  * @param alg The algorithm name associated with the key type
76  * @returns The new ML_DSA_KEY object on success, or NULL on malloc failure
77  */
ossl_ml_dsa_key_new(OSSL_LIB_CTX * libctx,const char * propq,int evp_type)78 ML_DSA_KEY *ossl_ml_dsa_key_new(OSSL_LIB_CTX *libctx, const char *propq,
79                                 int evp_type)
80 {
81     ML_DSA_KEY *ret;
82     const ML_DSA_PARAMS *params = ossl_ml_dsa_params_get(evp_type);
83 
84     if (params == NULL)
85         return NULL;
86 
87     ret = OPENSSL_zalloc(sizeof(*ret));
88     if (ret != NULL) {
89         ret->libctx = libctx;
90         ret->params = params;
91         ret->prov_flags = ML_DSA_KEY_PROV_FLAGS_DEFAULT;
92         ret->shake128_md = EVP_MD_fetch(libctx, "SHAKE-128", propq);
93         ret->shake256_md = EVP_MD_fetch(libctx, "SHAKE-256", propq);
94         if (ret->shake128_md == NULL || ret->shake256_md == NULL)
95             goto err;
96     }
97     return ret;
98 err:
99     ossl_ml_dsa_key_free(ret);
100     return NULL;
101 }
102 
ossl_ml_dsa_key_pub_alloc(ML_DSA_KEY * key)103 int ossl_ml_dsa_key_pub_alloc(ML_DSA_KEY *key)
104 {
105     if (key->t1.poly != NULL)
106         return 0;
107     return vector_alloc(&key->t1, key->params->k);
108 }
109 
ossl_ml_dsa_key_priv_alloc(ML_DSA_KEY * key)110 int ossl_ml_dsa_key_priv_alloc(ML_DSA_KEY *key)
111 {
112     size_t k = key->params->k, l = key->params->l;
113     POLY *poly;
114 
115     if (key->s1.poly != NULL)
116         return 0;
117     if (!vector_alloc(&key->s1, l + 2 * k))
118         return 0;
119 
120     poly = key->s1.poly;
121     key->s1.num_poly = l;
122     vector_init(&key->s2, poly + l, k);
123     vector_init(&key->t0, poly + l + k, k);
124     return 1;
125 }
126 
127 /**
128  * @brief Destroy an ML_DSA_KEY object
129  */
ossl_ml_dsa_key_free(ML_DSA_KEY * key)130 void ossl_ml_dsa_key_free(ML_DSA_KEY *key)
131 {
132     if (key == NULL)
133         return;
134 
135     EVP_MD_free(key->shake128_md);
136     EVP_MD_free(key->shake256_md);
137     ossl_ml_dsa_key_reset(key);
138     OPENSSL_free(key);
139 }
140 
141 /**
142  * @brief Factory reset an ML_DSA_KEY object
143  */
ossl_ml_dsa_key_reset(ML_DSA_KEY * key)144 void ossl_ml_dsa_key_reset(ML_DSA_KEY *key)
145 {
146     /*
147      * The allocation for |s1.poly| subsumes those for |s2| and |t0|, which we
148      * must not access after |s1|'s poly is freed.
149      */
150     if (key->s1.poly != NULL) {
151         vector_zero(&key->s1);
152         vector_zero(&key->s2);
153         vector_zero(&key->t0);
154         vector_free(&key->s1);
155         key->s2.poly = NULL;
156         key->t0.poly = NULL;
157     }
158     /* The |t1| vector is public and allocated separately */
159     vector_free(&key->t1);
160     OPENSSL_cleanse(key->K, sizeof(key->K));
161     OPENSSL_free(key->pub_encoding);
162     key->pub_encoding = NULL;
163     if (key->priv_encoding != NULL)
164         OPENSSL_clear_free(key->priv_encoding, key->params->sk_len);
165     key->priv_encoding = NULL;
166     if (key->seed != NULL)
167         OPENSSL_clear_free(key->seed, ML_DSA_SEED_BYTES);
168     key->seed = NULL;
169 }
170 
171 /**
172  * @brief Duplicate a key
173  *
174  * @param src A ML_DSA_KEY object to copy
175  * @param selection to select public and/or private components. Selecting the
176  *                  private key will also select the public key
177  * @returns The duplicated key, or NULL on failure.
178  */
ossl_ml_dsa_key_dup(const ML_DSA_KEY * src,int selection)179 ML_DSA_KEY *ossl_ml_dsa_key_dup(const ML_DSA_KEY *src, int selection)
180 {
181     ML_DSA_KEY *ret = NULL;
182 
183     if (src == NULL)
184         return NULL;
185 
186     /* Prekeys with just a seed or private key are not dupable */
187     if (src->pub_encoding == NULL
188         && (src->priv_encoding != NULL || src->seed != NULL))
189         return NULL;
190 
191     ret = OPENSSL_zalloc(sizeof(*ret));
192     if (ret != NULL) {
193         ret->libctx = src->libctx;
194         ret->params = src->params;
195         ret->prov_flags = src->prov_flags;
196         if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
197             if (src->pub_encoding != NULL) {
198                 /* The public components are present if the private key is present */
199                 memcpy(ret->rho, src->rho, sizeof(src->rho));
200                 memcpy(ret->tr, src->tr, sizeof(src->tr));
201                 if (src->t1.poly != NULL) {
202                     if (!ossl_ml_dsa_key_pub_alloc(ret))
203                         goto err;
204                     vector_copy(&ret->t1, &src->t1);
205                 }
206                 if ((ret->pub_encoding = OPENSSL_memdup(src->pub_encoding,
207                                                         src->params->pk_len)) == NULL)
208                     goto err;
209             }
210             if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
211                 if (src->priv_encoding != NULL) {
212                     memcpy(ret->K, src->K, sizeof(src->K));
213                     if (src->s1.poly != NULL) {
214                         if (!ossl_ml_dsa_key_priv_alloc(ret))
215                             goto err;
216                         vector_copy(&ret->s1, &src->s1);
217                         vector_copy(&ret->s2, &src->s2);
218                         vector_copy(&ret->t0, &src->t0);
219                     }
220                     if ((ret->priv_encoding =
221                             OPENSSL_memdup(src->priv_encoding,
222                                            src->params->sk_len)) == NULL)
223                         goto err;
224                 }
225                 if (src->seed != NULL
226                     && (ret->seed = OPENSSL_memdup(src->seed,
227                                                    ML_DSA_SEED_BYTES)) == NULL)
228                     goto err;
229             }
230         }
231         EVP_MD_up_ref(src->shake128_md);
232         EVP_MD_up_ref(src->shake256_md);
233         ret->shake128_md = src->shake128_md;
234         ret->shake256_md = src->shake256_md;
235     }
236     return ret;
237  err:
238     ossl_ml_dsa_key_free(ret);
239     return NULL;
240 }
241 
242 /**
243  * @brief Are 2 keys equal?
244  *
245  * To be equal the keys must have matching public or private key data and
246  * contain the same parameters.
247  * (Note that in OpenSSL that the private key always has a public key component).
248  *
249  * @param key1 A ML_DSA_KEY object
250  * @param key2 A ML_DSA_KEY object
251  * @param selection to select public and/or private component comparison.
252  * @returns 1 if the keys are equal otherwise it returns 0.
253  */
ossl_ml_dsa_key_equal(const ML_DSA_KEY * key1,const ML_DSA_KEY * key2,int selection)254 int ossl_ml_dsa_key_equal(const ML_DSA_KEY *key1, const ML_DSA_KEY *key2,
255                           int selection)
256 {
257     int key_checked = 0;
258 
259     if (key1->params != key2->params)
260         return 0;
261 
262     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
263         if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
264             if (key1->pub_encoding != NULL && key2->pub_encoding != NULL) {
265                 if (memcmp(key1->pub_encoding, key2->pub_encoding,
266                                   key1->params->pk_len) != 0)
267                     return 0;
268                 key_checked = 1;
269             }
270         }
271         if (!key_checked
272                 && (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
273             if (key1->priv_encoding != NULL && key2->priv_encoding != NULL) {
274                 if (memcmp(key1->priv_encoding, key2->priv_encoding,
275                            key1->params->sk_len) != 0)
276                     return 0;
277                 key_checked = 1;
278             }
279         }
280         return key_checked;
281     }
282     return 1;
283 }
284 
ossl_ml_dsa_key_has(const ML_DSA_KEY * key,int selection)285 int ossl_ml_dsa_key_has(const ML_DSA_KEY *key, int selection)
286 {
287     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
288         /* Note that the public key always exists if there is a private key */
289         if (ossl_ml_dsa_key_get_pub(key) == NULL)
290             return 0; /* No public key */
291         if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
292                 && ossl_ml_dsa_key_get_priv(key) == NULL)
293             return 0; /* No private key */
294         return 1;
295     }
296     return 0;
297 }
298 
299 /*
300  * @brief Given a key containing private key values for rho, s1 & s2
301  * generate the public value t and return the compressed values t1, t0.
302  *
303  * @param key A private key containing params, rh0, s1 & s2.
304  * @param md_ctx A EVP_MD_CTX used for sampling.
305  * @param t1 The returned polynomial encoding of the 10 MSB of each coefficient
306  *        of the uncompressed public key polynomial t.
307  * @param t0 The returned polynomial encoding of the 13 LSB of each coefficient
308  *        of the uncompressed public key polynomial t.
309  * @returns 1 on success, or 0 on failure.
310  */
public_from_private(const ML_DSA_KEY * key,EVP_MD_CTX * md_ctx,VECTOR * t1,VECTOR * t0)311 static int public_from_private(const ML_DSA_KEY *key, EVP_MD_CTX *md_ctx,
312                                VECTOR *t1, VECTOR *t0)
313 {
314     int ret = 0;
315     const ML_DSA_PARAMS *params = key->params;
316     uint32_t k = params->k, l = params->l;
317     POLY *polys;
318     MATRIX a_ntt;
319     VECTOR s1_ntt;
320     VECTOR t;
321 
322     polys = OPENSSL_malloc(sizeof(*polys) * (k + l + k * l));
323     if (polys == NULL)
324         return 0;
325 
326     vector_init(&t, polys, k);
327     vector_init(&s1_ntt, t.poly + k, l);
328     matrix_init(&a_ntt, s1_ntt.poly + l, k, l);
329 
330     /* Using rho generate A' = A in NTT form */
331     if (!matrix_expand_A(md_ctx, key->shake128_md, key->rho, &a_ntt))
332         goto err;
333 
334     /* t = NTT_inv(A' * NTT(s1)) + s2 */
335     vector_copy(&s1_ntt, &key->s1);
336     vector_ntt(&s1_ntt);
337 
338     matrix_mult_vector(&a_ntt, &s1_ntt, &t);
339     vector_ntt_inverse(&t);
340     vector_add(&t, &key->s2, &t);
341 
342     /* Compress t */
343     vector_power2_round(&t, t1, t0);
344 
345     /* Zeroize secret */
346     vector_zero(&s1_ntt);
347     ret = 1;
348 err:
349     OPENSSL_free(polys);
350     return ret;
351 }
352 
ossl_ml_dsa_key_public_from_private(ML_DSA_KEY * key)353 int ossl_ml_dsa_key_public_from_private(ML_DSA_KEY *key)
354 {
355     int ret = 0;
356     VECTOR t0;
357     EVP_MD_CTX *md_ctx = NULL;
358 
359     if (!vector_alloc(&t0, key->params->k)) /* t0 is already in the private key */
360         return 0;
361     ret = ((md_ctx = EVP_MD_CTX_new())!= NULL)
362         && ossl_ml_dsa_key_pub_alloc(key)  /* allocate space for t1 */
363         && public_from_private(key, md_ctx, &key->t1, &t0)
364         && vector_equal(&t0, &key->t0) /* compare the generated t0 to the expected */
365         && ossl_ml_dsa_pk_encode(key)
366         && shake_xof(md_ctx, key->shake256_md,
367                      key->pub_encoding, key->params->pk_len,
368                      key->tr, sizeof(key->tr));
369     vector_free(&t0);
370     EVP_MD_CTX_free(md_ctx);
371     return ret;
372 }
373 
ossl_ml_dsa_key_pairwise_check(const ML_DSA_KEY * key)374 int ossl_ml_dsa_key_pairwise_check(const ML_DSA_KEY *key)
375 {
376     int ret = 0;
377     VECTOR t1, t0;
378     POLY *polys = NULL;
379     uint32_t k = key->params->k;
380     EVP_MD_CTX *md_ctx = NULL;
381 
382     if (key->pub_encoding == NULL || key->priv_encoding == 0)
383         return 0;
384 
385     polys = OPENSSL_malloc(sizeof(*polys) * (2 * k));
386     if (polys == NULL)
387         return 0;
388     md_ctx = EVP_MD_CTX_new();
389     if (md_ctx == NULL)
390         goto err;
391 
392     vector_init(&t1, polys, k);
393     vector_init(&t0, polys + k, k);
394     if (!public_from_private(key, md_ctx, &t1, &t0))
395         goto err;
396 
397     ret = vector_equal(&t1, &key->t1) && vector_equal(&t0, &key->t0);
398 err:
399     EVP_MD_CTX_free(md_ctx);
400     OPENSSL_free(polys);
401     return ret;
402 }
403 
404 /*
405  * @brief Generate a public-private key pair from a seed.
406  * See FIPS 204, Algorithm 6 ML-DSA.KeyGen_internal().
407  *
408  * @param out The generated key (which contains params on input)
409  *
410  * @returns 1 on success or 0 on failure.
411  */
keygen_internal(ML_DSA_KEY * out)412 static int keygen_internal(ML_DSA_KEY *out)
413 {
414     int ret = 0;
415     uint8_t augmented_seed[ML_DSA_SEED_BYTES + 2];
416     uint8_t expanded_seed[ML_DSA_RHO_BYTES + ML_DSA_PRIV_SEED_BYTES + ML_DSA_K_BYTES];
417     const uint8_t *const rho = expanded_seed; /* p = Public Random Seed */
418     const uint8_t *const priv_seed = expanded_seed + ML_DSA_RHO_BYTES;
419     const uint8_t *const K = priv_seed + ML_DSA_PRIV_SEED_BYTES;
420     const ML_DSA_PARAMS *params = out->params;
421     EVP_MD_CTX *md_ctx = NULL;
422 
423     if (out->seed == NULL
424         || (md_ctx = EVP_MD_CTX_new()) == NULL
425         || !ossl_ml_dsa_key_pub_alloc(out)
426         || !ossl_ml_dsa_key_priv_alloc(out))
427         goto err;
428 
429     /* augmented_seed = seed || k || l */
430     memcpy(augmented_seed, out->seed, ML_DSA_SEED_BYTES);
431     augmented_seed[ML_DSA_SEED_BYTES] = (uint8_t)params->k;
432     augmented_seed[ML_DSA_SEED_BYTES + 1] = (uint8_t)params->l;
433     /* Expand the seed into p[32], p'[64], K[32] */
434     if (!shake_xof(md_ctx, out->shake256_md, augmented_seed, sizeof(augmented_seed),
435                    expanded_seed, sizeof(expanded_seed)))
436         goto err;
437 
438     memcpy(out->rho, rho, sizeof(out->rho));
439     memcpy(out->K, K, sizeof(out->K));
440 
441     ret = vector_expand_S(md_ctx, out->shake256_md, params->eta, priv_seed, &out->s1, &out->s2)
442         && public_from_private(out, md_ctx, &out->t1, &out->t0)
443         && ossl_ml_dsa_pk_encode(out)
444         && shake_xof(md_ctx, out->shake256_md, out->pub_encoding, out->params->pk_len,
445                      out->tr, sizeof(out->tr))
446         && ossl_ml_dsa_sk_encode(out);
447 
448 err:
449     if (out->seed != NULL && (out->prov_flags & ML_DSA_KEY_RETAIN_SEED) == 0) {
450         OPENSSL_clear_free(out->seed, ML_DSA_SEED_BYTES);
451         out->seed = NULL;
452     }
453     EVP_MD_CTX_free(md_ctx);
454     OPENSSL_cleanse(augmented_seed, sizeof(augmented_seed));
455     OPENSSL_cleanse(expanded_seed, sizeof(expanded_seed));
456     return ret;
457 }
458 
ossl_ml_dsa_generate_key(ML_DSA_KEY * out)459 int ossl_ml_dsa_generate_key(ML_DSA_KEY *out)
460 {
461     size_t seed_len = ML_DSA_SEED_BYTES;
462     uint8_t *sk;
463     int ret;
464 
465     if (out->seed == NULL) {
466         if ((out->seed = OPENSSL_malloc(seed_len)) == NULL)
467             return 0;
468         if (RAND_priv_bytes_ex(out->libctx, out->seed, seed_len, 0) <= 0) {
469             OPENSSL_free(out->seed);
470             out->seed = NULL;
471             return 0;
472         }
473     }
474     /* We're generating from a seed, drop private prekey encoding */
475     sk = out->priv_encoding;
476     out->priv_encoding = NULL;
477     if (sk == NULL) {
478         ret = keygen_internal(out);
479     } else {
480         if ((ret = keygen_internal(out)) != 0
481             && memcmp(out->priv_encoding, sk, out->params->sk_len) != 0) {
482             ret = 0;
483             ossl_ml_dsa_key_reset(out);
484             ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
485                            "explicit %s private key does not match seed",
486                            out->params->alg);
487         }
488         OPENSSL_free(sk);
489     }
490     return ret;
491 }
492 
493 /**
494  * @brief This is used when a ML DSA key is used for an operation.
495  * This checks that the algorithm is the same (i.e. uses the same parameters)
496  *
497  * @param key A ML_DSA key to use for an operation.
498  * @param evp_type The algorithm nid associated with an operation
499  *
500  * @returns 1 if the algorithm matches, or 0 otherwise.
501  */
502 
ossl_ml_dsa_key_matches(const ML_DSA_KEY * key,int evp_type)503 int ossl_ml_dsa_key_matches(const ML_DSA_KEY *key, int evp_type)
504 {
505     return (key->params->evp_type == evp_type);
506 }
507 
508 /* Returns the public key data or NULL if there is no public key */
ossl_ml_dsa_key_get_pub(const ML_DSA_KEY * key)509 const uint8_t *ossl_ml_dsa_key_get_pub(const ML_DSA_KEY *key)
510 {
511     return key->pub_encoding;
512 }
513 
514 /* Returns the encoded public key size */
ossl_ml_dsa_key_get_pub_len(const ML_DSA_KEY * key)515 size_t ossl_ml_dsa_key_get_pub_len(const ML_DSA_KEY *key)
516 {
517     return key->params->pk_len;
518 }
519 
ossl_ml_dsa_key_get_collision_strength_bits(const ML_DSA_KEY * key)520 size_t ossl_ml_dsa_key_get_collision_strength_bits(const ML_DSA_KEY *key)
521 {
522     return key->params->bit_strength;
523 }
524 
525 /* Returns the private key data or NULL if there is no private key */
ossl_ml_dsa_key_get_priv(const ML_DSA_KEY * key)526 const uint8_t *ossl_ml_dsa_key_get_priv(const ML_DSA_KEY *key)
527 {
528     return key->priv_encoding;
529 }
530 
ossl_ml_dsa_key_get_priv_len(const ML_DSA_KEY * key)531 size_t ossl_ml_dsa_key_get_priv_len(const ML_DSA_KEY *key)
532 {
533     return key->params->sk_len;
534 }
535 
ossl_ml_dsa_key_get_sig_len(const ML_DSA_KEY * key)536 size_t ossl_ml_dsa_key_get_sig_len(const ML_DSA_KEY *key)
537 {
538     return key->params->sig_len;
539 }
540 
ossl_ml_dsa_key_get0_libctx(const ML_DSA_KEY * key)541 OSSL_LIB_CTX *ossl_ml_dsa_key_get0_libctx(const ML_DSA_KEY *key)
542 {
543     return key != NULL ? key->libctx : NULL;
544 }
545 
ossl_ml_dsa_key_get_name(const ML_DSA_KEY * key)546 const char *ossl_ml_dsa_key_get_name(const ML_DSA_KEY *key)
547 {
548     return key->params->alg;
549 }
550