Coverage Report

Created: 2026-02-22 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/ml_dsa/ml_dsa_sign.c
Line
Count
Source
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/params.h>
13
#include <openssl/rand.h>
14
#include <openssl/err.h>
15
#include <openssl/proverr.h>
16
#include "internal/common.h"
17
#include "ml_dsa_local.h"
18
#include "ml_dsa_key.h"
19
#include "ml_dsa_matrix.h"
20
#include "ml_dsa_sign.h"
21
#include "ml_dsa_hash.h"
22
23
#define ML_DSA_MAX_LAMBDA 256 /* bit strength for ML-DSA-87 */
24
25
/*
26
 * @brief Initialize a Signature object by pointing all of its objects to
27
 * preallocated blocks. The values passed for hint, z and
28
 * c_tilde values are not owned/freed by the |sig| object.
29
 *
30
 * @param sig The ML_DSA_SIG to initialize.
31
 * @param hint A preallocated array of |k| polynomial blocks
32
 * @param k The number of |hint| polynomials
33
 * @param z A preallocated array of |l| polynomial blocks
34
 * @param l The number of |z| polynomials
35
 * @param c_tilde A preallocated buffer
36
 * @param c_tilde_len The size of |c_tilde|
37
 */
38
static void signature_init(ML_DSA_SIG *sig,
39
    POLY *hint, uint32_t k, POLY *z, uint32_t l,
40
    uint8_t *c_tilde, size_t c_tilde_len)
41
0
{
42
0
    vector_init(&sig->z, z, l);
43
0
    vector_init(&sig->hint, hint, k);
44
0
    sig->c_tilde = c_tilde;
45
0
    sig->c_tilde_len = c_tilde_len;
46
0
}
47
48
/*
49
 * @brief: Auxiliary functions to compute ML-DSA's MU.
50
 * This combines the steps of creating M' and concatenating it
51
 * to the Public Key Hash to obtain MU.
52
 * See FIPS 204 Algorithm 2 Step 10 (and algorithm 3 Step 5) as
53
 * well as Algorithm 7 Step 6 (and algorithm 8 Step 7)
54
 *
55
 * ML_DSA pure signatures are encoded as M' = 00 || ctx_len || ctx || msg
56
 * Where ctx is the empty string by default and ctx_len <= 255.
57
 * The message is appended to the encoded context.
58
 * Finally a public key hash is prepended, and the whole is hashed
59
 * to derive the mu value.
60
 *
61
 * @param key: A public or private ML-DSA key;
62
 * @param encode: if not set, assumes that M' is provided raw and the
63
 * following parameters are ignored.
64
 * @param ctx An optional context to add to the message encoding.
65
 * @param ctx_len The size of |ctx|. It must be in the range 0..255
66
 * @returns an EVP_MD_CTX if the operation is successful, NULL otherwise.
67
 */
68
EVP_MD_CTX *ossl_ml_dsa_mu_init_int(EVP_MD *shake256_md,
69
    const uint8_t *tr, size_t tr_len, int encode, int prehash,
70
    const uint8_t *ctx, size_t ctx_len)
71
0
{
72
0
    EVP_MD_CTX *md_ctx;
73
0
    uint8_t itb[2];
74
75
0
    md_ctx = EVP_MD_CTX_new();
76
0
    if (md_ctx == NULL)
77
0
        return NULL;
78
79
    /* H(.. */
80
0
    if (!EVP_DigestInit_ex2(md_ctx, shake256_md, NULL))
81
0
        goto err;
82
    /* ..pk (= key->tr) */
83
0
    if (!EVP_DigestUpdate(md_ctx, tr, tr_len))
84
0
        goto err;
85
    /* M' = .. */
86
0
    if (encode) {
87
0
        if (ctx_len > ML_DSA_MAX_CONTEXT_STRING_LEN)
88
0
            goto err;
89
        /* IntegerToBytes(0, 1) .. */
90
0
        itb[0] = prehash ? 1 : 0;
91
        /* || IntegerToBytes(|ctx|, 1) || .. */
92
0
        itb[1] = (uint8_t)ctx_len;
93
0
        if (!EVP_DigestUpdate(md_ctx, itb, 2))
94
0
            goto err;
95
        /* ctx || .. */
96
0
        if (!EVP_DigestUpdate(md_ctx, ctx, ctx_len))
97
0
            goto err;
98
        /* .. msg) will follow in update and final functions */
99
0
    }
100
101
0
    return md_ctx;
102
103
0
err:
104
0
    EVP_MD_CTX_free(md_ctx);
105
0
    return NULL;
106
0
}
107
108
EVP_MD_CTX *ossl_ml_dsa_mu_init(const ML_DSA_KEY *key, int encode,
109
    const uint8_t *ctx, size_t ctx_len)
110
0
{
111
0
    if (key == NULL)
112
0
        return NULL;
113
0
    return ossl_ml_dsa_mu_init_int(key->shake256_md, key->tr, sizeof(key->tr),
114
0
        encode, 0, ctx, ctx_len);
115
0
}
116
117
/*
118
 * @brief: updates the internal ML-DSA hash with an additional message chunk.
119
 *
120
 * @param md_ctx: The hashing context
121
 * @param msg: The next message chunk
122
 * @param msg_len: The length of the msg buffer to process
123
 * @returns 1 on success, 0 on error
124
 */
125
int ossl_ml_dsa_mu_update(EVP_MD_CTX *md_ctx, const uint8_t *msg, size_t msg_len)
126
0
{
127
0
    return EVP_DigestUpdate(md_ctx, msg, msg_len);
128
0
}
129
130
/*
131
 * @brief: finalizes the internal ML-DSA hash
132
 *
133
 * @param md_ctx: The hashing context
134
 * @param mu: The output buffer for Mu
135
 * @param mu_len: The size of the output buffer
136
 * @returns 1 on success, 0 on error
137
 */
138
int ossl_ml_dsa_mu_finalize(EVP_MD_CTX *md_ctx, uint8_t *mu, size_t mu_len)
139
0
{
140
0
    if (!ossl_assert(mu_len == ML_DSA_MU_BYTES)) {
141
0
        ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
142
0
        return 0;
143
0
    }
144
0
    return EVP_DigestSqueeze(md_ctx, mu, mu_len);
145
0
}
146
147
/*
148
 * @brief FIPS 204, Algorithm 7, ML-DSA.Sign_internal()
149
 *
150
 * This algorithm is decomposed in 2 steps, a set of functions to compute mu
151
 * and then the actual signing function.
152
 *
153
 * @param priv: The private ML-DSA key
154
 * @param mu: The pre-computed mu hash
155
 * @param mu_len: The length of the mu buffer
156
 * @param rnd: The random buffer
157
 * @param rnd_len: The length of the random buffer
158
 * @param out_sig: The output signature buffer
159
 * @returns 1 on success, 0 on error
160
 */
161
static int ml_dsa_sign_internal(const ML_DSA_KEY *priv,
162
    const uint8_t *mu, size_t mu_len, const uint8_t *rnd, size_t rnd_len,
163
    uint8_t *out_sig)
164
0
{
165
0
    int ret = 0;
166
0
    const ML_DSA_PARAMS *params = priv->params;
167
0
    EVP_MD_CTX *md_ctx = NULL;
168
0
    uint32_t k = (uint32_t)params->k, l = (uint32_t)params->l;
169
0
    uint32_t gamma1 = params->gamma1, gamma2 = params->gamma2;
170
0
    uint8_t *alloc = NULL, *w1_encoded;
171
0
    size_t alloc_len, w1_encoded_len;
172
0
    size_t num_polys_sig_k = 2 * k;
173
0
    size_t num_polys_k = 5 * k;
174
0
    size_t num_polys_l = 3 * l;
175
0
    size_t num_polys_k_by_l = k * l;
176
0
    POLY *p, *c_ntt;
177
0
    VECTOR s1_ntt, s2_ntt, t0_ntt, w, w1, cs1, cs2, y;
178
0
    MATRIX a_ntt;
179
0
    ML_DSA_SIG sig;
180
0
    uint8_t rho_prime[ML_DSA_RHO_PRIME_BYTES];
181
0
    uint8_t c_tilde[ML_DSA_MAX_LAMBDA / 4];
182
0
    size_t c_tilde_len = params->bit_strength >> 2;
183
0
    size_t kappa;
184
185
0
    if (mu_len != ML_DSA_MU_BYTES) {
186
0
        ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
187
0
        return 0;
188
0
    }
189
190
    /*
191
     * Allocate a single blob for most of the variable size temporary variables.
192
     * Mostly used for VECTOR POLYNOMIALS (every POLY is 1K).
193
     */
194
0
    w1_encoded_len = k * (gamma2 == ML_DSA_GAMMA2_Q_MINUS1_DIV88 ? 192 : 128);
195
0
    alloc_len = w1_encoded_len
196
0
        + sizeof(*p) * (1 + num_polys_k + num_polys_l + num_polys_k_by_l + num_polys_sig_k);
197
0
    alloc = OPENSSL_malloc(alloc_len);
198
0
    if (alloc == NULL)
199
0
        return 0;
200
0
    md_ctx = EVP_MD_CTX_new();
201
0
    if (md_ctx == NULL)
202
0
        goto err;
203
204
0
    w1_encoded = alloc;
205
    /* Init the temp vectors to point to the allocated polys blob */
206
0
    p = (POLY *)(w1_encoded + w1_encoded_len);
207
0
    c_ntt = p++;
208
0
    matrix_init(&a_ntt, p, k, l);
209
0
    p += num_polys_k_by_l;
210
0
    vector_init(&s2_ntt, p, k);
211
0
    vector_init(&t0_ntt, s2_ntt.poly + k, k);
212
0
    vector_init(&w, t0_ntt.poly + k, k);
213
0
    vector_init(&w1, w.poly + k, k);
214
0
    vector_init(&cs2, w1.poly + k, k);
215
0
    p += num_polys_k;
216
0
    vector_init(&s1_ntt, p, l);
217
0
    vector_init(&y, p + l, l);
218
0
    vector_init(&cs1, p + 2 * l, l);
219
0
    p += num_polys_l;
220
0
    signature_init(&sig, p, k, p + k, l, c_tilde, c_tilde_len);
221
    /* End of the allocated blob setup */
222
223
0
    if (!matrix_expand_A(md_ctx, priv->shake128_md, priv->rho, &a_ntt))
224
0
        goto err;
225
226
0
    if (!shake_xof_3(md_ctx, priv->shake256_md, priv->K, sizeof(priv->K),
227
0
            rnd, rnd_len, mu, mu_len,
228
0
            rho_prime, sizeof(rho_prime)))
229
0
        goto err;
230
231
0
    vector_copy(&s1_ntt, &priv->s1);
232
0
    vector_ntt(&s1_ntt);
233
0
    vector_copy(&s2_ntt, &priv->s2);
234
0
    vector_ntt(&s2_ntt);
235
0
    vector_copy(&t0_ntt, &priv->t0);
236
0
    vector_ntt(&t0_ntt);
237
238
    /*
239
     * kappa must not exceed 2^16. But the probability of it
240
     * exceeding even 1000 iterations is vanishingly small.
241
     */
242
0
    for (kappa = 0;; kappa += l) {
243
0
        VECTOR *y_ntt = &cs1;
244
0
        VECTOR *r0 = &w1;
245
0
        VECTOR *ct0 = &w1;
246
0
        uint32_t z_max, r0_max, ct0_max, h_ones;
247
248
0
        vector_expand_mask(&y, rho_prime, sizeof(rho_prime), (uint32_t)kappa,
249
0
            gamma1, md_ctx, priv->shake256_md);
250
0
        vector_copy(y_ntt, &y);
251
0
        vector_ntt(y_ntt);
252
253
0
        matrix_mult_vector(&a_ntt, y_ntt, &w);
254
0
        vector_ntt_inverse(&w);
255
256
0
        vector_high_bits(&w, gamma2, &w1);
257
0
        ossl_ml_dsa_w1_encode(&w1, gamma2, w1_encoded, w1_encoded_len);
258
259
0
        if (!shake_xof_2(md_ctx, priv->shake256_md, mu, mu_len,
260
0
                w1_encoded, w1_encoded_len, c_tilde, c_tilde_len))
261
0
            break;
262
263
0
        if (!poly_sample_in_ball_ntt(c_ntt, c_tilde, (int)c_tilde_len,
264
0
                md_ctx, priv->shake256_md, params->tau))
265
0
            break;
266
267
0
        vector_mult_scalar(&s1_ntt, c_ntt, &cs1);
268
0
        vector_ntt_inverse(&cs1);
269
0
        vector_mult_scalar(&s2_ntt, c_ntt, &cs2);
270
0
        vector_ntt_inverse(&cs2);
271
272
0
        vector_add(&y, &cs1, &sig.z);
273
274
        /* r0 = lowbits(w - cs2) */
275
0
        vector_sub(&w, &cs2, r0);
276
0
        vector_low_bits(r0, gamma2, r0);
277
278
        /*
279
         * Leaking that the signature is rejected is fine as the next attempt at a
280
         * signature will be (indistinguishable from) independent of this one.
281
         */
282
0
        z_max = vector_max(&sig.z);
283
0
        r0_max = vector_max_signed(r0);
284
0
        if (value_barrier_32(constant_time_ge(z_max, gamma1 - params->beta)
285
0
                | constant_time_ge(r0_max, gamma2 - params->beta)))
286
0
            continue;
287
288
0
        vector_mult_scalar(&t0_ntt, c_ntt, ct0);
289
0
        vector_ntt_inverse(ct0);
290
0
        vector_make_hint(ct0, &cs2, &w, gamma2, &sig.hint);
291
292
0
        ct0_max = vector_max(ct0);
293
0
        h_ones = (uint32_t)vector_count_ones(&sig.hint);
294
        /* Same reasoning applies to the leak as above */
295
0
        if (value_barrier_32(constant_time_ge(ct0_max, gamma2)
296
0
                | constant_time_lt(params->omega, h_ones)))
297
0
            continue;
298
0
        ret = ossl_ml_dsa_sig_encode(&sig, params, out_sig);
299
0
        break;
300
0
    }
301
0
err:
302
0
    EVP_MD_CTX_free(md_ctx);
303
0
    OPENSSL_clear_free(alloc, alloc_len);
304
0
    OPENSSL_cleanse(rho_prime, sizeof(rho_prime));
305
0
    return ret;
306
0
}
307
308
/*
309
 * @brief FIPS 204, Algorithm 8, ML-DSA.Verify_internal().
310
 *
311
 * This algorithm is decomposed in 2 steps, a set of functions to compute mu
312
 * and then the actual verification function.
313
 *
314
 * @param pub: The public ML-DSA key
315
 * @param mu: The pre-computed mu hash
316
 * @param mu_len: The length of the mu buffer
317
 * @param sig_enc: The encoded signature to be verified
318
 * @param sig_enc_len: the encoded csignature length
319
 * @returns 1 on success, 0 on error
320
 */
321
static int ml_dsa_verify_internal(const ML_DSA_KEY *pub,
322
    const uint8_t *mu, size_t mu_len,
323
    const uint8_t *sig_enc, size_t sig_enc_len)
324
0
{
325
0
    int ret = 0;
326
0
    uint8_t *alloc = NULL, *w1_encoded;
327
0
    POLY *p, *c_ntt;
328
0
    MATRIX a_ntt;
329
0
    VECTOR az_ntt, ct1_ntt, *z_ntt, *w1, *w_approx;
330
0
    ML_DSA_SIG sig;
331
0
    const ML_DSA_PARAMS *params = pub->params;
332
0
    uint32_t k = (uint32_t)pub->params->k;
333
0
    uint32_t l = (uint32_t)pub->params->l;
334
0
    uint32_t gamma2 = params->gamma2;
335
0
    size_t w1_encoded_len;
336
0
    size_t num_polys_sig = k + l;
337
0
    size_t num_polys_k = 2 * k;
338
0
    size_t num_polys_l = 1 * l;
339
0
    size_t num_polys_k_by_l = k * l;
340
0
    uint8_t c_tilde[ML_DSA_MAX_LAMBDA / 4];
341
0
    uint8_t c_tilde_sig[ML_DSA_MAX_LAMBDA / 4];
342
0
    EVP_MD_CTX *md_ctx = NULL;
343
0
    size_t c_tilde_len = params->bit_strength >> 2;
344
0
    uint32_t z_max;
345
346
    /* FIPS 204 compliance: Also validate signature length before decoding */
347
0
    if (mu_len != ML_DSA_MU_BYTES || sig_enc_len != params->sig_len) {
348
0
        ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
349
0
        return 0;
350
0
    }
351
352
    /* Allocate space for all the POLYNOMIALS used by temporary VECTORS */
353
0
    w1_encoded_len = k * (gamma2 == ML_DSA_GAMMA2_Q_MINUS1_DIV88 ? 192 : 128);
354
0
    alloc = OPENSSL_malloc(w1_encoded_len
355
0
        + sizeof(*p) * (1 + num_polys_k + num_polys_l + num_polys_k_by_l + num_polys_sig));
356
0
    if (alloc == NULL)
357
0
        return 0;
358
0
    md_ctx = EVP_MD_CTX_new();
359
0
    if (md_ctx == NULL)
360
0
        goto err;
361
362
0
    w1_encoded = alloc;
363
    /* Init the temp vectors to point to the allocated polys blob */
364
0
    p = (POLY *)(w1_encoded + w1_encoded_len);
365
0
    c_ntt = p++;
366
0
    matrix_init(&a_ntt, p, k, l);
367
0
    p += num_polys_k_by_l;
368
0
    signature_init(&sig, p, k, p + k, l, c_tilde_sig, c_tilde_len);
369
0
    p += num_polys_sig;
370
0
    vector_init(&az_ntt, p, k);
371
0
    vector_init(&ct1_ntt, p + k, k);
372
373
0
    if (!ossl_ml_dsa_sig_decode(&sig, sig_enc, sig_enc_len, pub->params)
374
0
        || !matrix_expand_A(md_ctx, pub->shake128_md, pub->rho, &a_ntt))
375
0
        goto err;
376
377
    /* Compute verifiers challenge c_ntt = NTT(SampleInBall(c_tilde)) */
378
0
    if (!poly_sample_in_ball_ntt(c_ntt, c_tilde_sig, (int)c_tilde_len,
379
0
            md_ctx, pub->shake256_md, params->tau))
380
0
        goto err;
381
382
    /* ct1_ntt = NTT(c) * NTT(t1 * 2^d) */
383
0
    vector_scale_power2_round_ntt(&pub->t1, &ct1_ntt);
384
0
    vector_mult_scalar(&ct1_ntt, c_ntt, &ct1_ntt);
385
386
    /* compute z_max early in order to reuse sig.z */
387
0
    z_max = vector_max(&sig.z);
388
389
    /* w_approx = NTT_inverse(A * NTT(z) - ct1_ntt) */
390
0
    z_ntt = &sig.z;
391
0
    vector_ntt(z_ntt);
392
0
    matrix_mult_vector(&a_ntt, z_ntt, &az_ntt);
393
0
    w_approx = &az_ntt;
394
0
    vector_sub(&az_ntt, &ct1_ntt, w_approx);
395
0
    vector_ntt_inverse(w_approx);
396
397
    /* compute w1_encoded */
398
0
    w1 = w_approx;
399
0
    vector_use_hint(&sig.hint, w_approx, gamma2, w1);
400
0
    ossl_ml_dsa_w1_encode(w1, gamma2, w1_encoded, w1_encoded_len);
401
402
0
    if (!shake_xof_3(md_ctx, pub->shake256_md, mu, mu_len,
403
0
            w1_encoded, w1_encoded_len, NULL, 0, c_tilde, c_tilde_len))
404
0
        goto err;
405
406
0
    ret = (z_max < (uint32_t)(params->gamma1 - params->beta))
407
0
        && memcmp(c_tilde, sig.c_tilde, c_tilde_len) == 0;
408
0
err:
409
0
    OPENSSL_free(alloc);
410
0
    EVP_MD_CTX_free(md_ctx);
411
0
    return ret;
412
0
}
413
414
/**
415
 * See FIPS 204 Section 5.2 Algorithm 2 ML-DSA.Sign()
416
 *
417
 * @returns 1 on success, or 0 on error.
418
 */
419
int ossl_ml_dsa_sign(const ML_DSA_KEY *priv,
420
    int msg_is_mu, const uint8_t *msg, size_t msg_len,
421
    const uint8_t *context, size_t context_len,
422
    const uint8_t *rand, size_t rand_len, int encode,
423
    unsigned char *sig, size_t *sig_len, size_t sig_size)
424
0
{
425
0
    EVP_MD_CTX *md_ctx = NULL;
426
0
    uint8_t mu[ML_DSA_MU_BYTES];
427
0
    const uint8_t *mu_ptr = mu;
428
0
    size_t mu_len = sizeof(mu);
429
0
    int ret = 0;
430
431
0
    if (ossl_ml_dsa_key_get_priv(priv) == NULL)
432
0
        return 0;
433
434
0
    if (sig_len != NULL)
435
0
        *sig_len = priv->params->sig_len;
436
437
0
    if (sig == NULL)
438
0
        return (sig_len != NULL) ? 1 : 0;
439
440
0
    if (sig_size < priv->params->sig_len)
441
0
        return 0;
442
443
0
    if (msg_is_mu) {
444
0
        mu_ptr = msg;
445
0
        mu_len = msg_len;
446
0
    } else {
447
0
        md_ctx = ossl_ml_dsa_mu_init(priv, encode, context, context_len);
448
0
        if (md_ctx == NULL)
449
0
            return 0;
450
451
0
        if (!ossl_ml_dsa_mu_update(md_ctx, msg, msg_len))
452
0
            goto err;
453
454
0
        if (!ossl_ml_dsa_mu_finalize(md_ctx, mu, mu_len))
455
0
            goto err;
456
0
    }
457
458
0
    ret = ml_dsa_sign_internal(priv, mu_ptr, mu_len, rand, rand_len, sig);
459
460
0
err:
461
0
    EVP_MD_CTX_free(md_ctx);
462
0
    return ret;
463
0
}
464
465
/**
466
 * See FIPS 203 Section 5.3 Algorithm 3 ML-DSA.Verify()
467
 * @returns 1 on success, or 0 on error.
468
 */
469
int ossl_ml_dsa_verify(const ML_DSA_KEY *pub,
470
    int msg_is_mu, const uint8_t *msg, size_t msg_len,
471
    const uint8_t *context, size_t context_len, int encode,
472
    const uint8_t *sig, size_t sig_len)
473
0
{
474
0
    EVP_MD_CTX *md_ctx = NULL;
475
0
    uint8_t mu[ML_DSA_MU_BYTES];
476
0
    const uint8_t *mu_ptr = mu;
477
0
    size_t mu_len = sizeof(mu);
478
0
    int ret = 0;
479
480
0
    if (ossl_ml_dsa_key_get_pub(pub) == NULL)
481
0
        return 0;
482
483
0
    if (msg_is_mu) {
484
0
        mu_ptr = msg;
485
0
        mu_len = msg_len;
486
0
    } else {
487
0
        md_ctx = ossl_ml_dsa_mu_init(pub, encode, context, context_len);
488
0
        if (md_ctx == NULL)
489
0
            return 0;
490
491
0
        if (!ossl_ml_dsa_mu_update(md_ctx, msg, msg_len))
492
0
            goto err;
493
494
0
        if (!ossl_ml_dsa_mu_finalize(md_ctx, mu, mu_len))
495
0
            goto err;
496
0
    }
497
498
0
    ret = ml_dsa_verify_internal(pub, mu_ptr, mu_len, sig, sig_len);
499
0
err:
500
0
    EVP_MD_CTX_free(md_ctx);
501
0
    return ret;
502
0
}