1 /*
2 * Copyright 2024-2026 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/byteorder.h>
11 #include <openssl/crypto.h>
12 #include "ml_dsa_local.h"
13 #include "ml_dsa_vector.h"
14 #include "ml_dsa_matrix.h"
15 #include "ml_dsa_hash.h"
16 #include "internal/sha3.h"
17 #include "internal/packet.h"
18
19 #define SHAKE128_BLOCKSIZE SHA3_BLOCKSIZE(128)
20 #define SHAKE256_BLOCKSIZE SHA3_BLOCKSIZE(256)
21
22 /*
23 * This is a constant time version of n % 5
24 * Note that 0xFFFF / 5 = 0x3333, 2 is added to make an over-estimate of 1/5
25 * and then we divide by (0xFFFF + 1)
26 */
27 #define MOD5(n) ((n) - 5 * (0x3335 * (n) >> 16))
28
29 #if SHAKE128_BLOCKSIZE % 3 != 0
30 #error "rej_ntt_poly() requires SHAKE128_BLOCKSIZE to be a multiple of 3"
31 #endif
32
33 typedef int(COEFF_FROM_NIBBLE_FUNC)(uint32_t nibble, uint32_t *out);
34
35 static COEFF_FROM_NIBBLE_FUNC coeff_from_nibble_4;
36 static COEFF_FROM_NIBBLE_FUNC coeff_from_nibble_2;
37
38 /**
39 * @brief Combine 3 bytes to form an coefficient.
40 * See FIPS 204, Algorithm 14, CoeffFromThreeBytes()
41 *
42 * This is not constant time as it is used to generate the matrix A which is public.
43 *
44 * @param s A byte array of 3 uniformly distributed bytes.
45 * @param out The returned coefficient in the range 0..q-1.
46 * @returns 1 if the value is less than q or 0 otherwise.
47 * This is used for rejection sampling.
48 */
coeff_from_three_bytes(const uint8_t * s,uint32_t * out)49 static ossl_inline int coeff_from_three_bytes(const uint8_t *s, uint32_t *out)
50 {
51 /* Zero out the top bit of the 3rd byte to get a value in the range 0..2^23-1) */
52 *out = (uint32_t)s[0] | ((uint32_t)s[1] << 8) | (((uint32_t)s[2] & 0x7f) << 16);
53 return *out < ML_DSA_Q;
54 }
55
56 /**
57 * @brief Generate a value in the range (q-4..0..4)
58 * See FIPS 204, Algorithm 15, CoeffFromHalfByte() where eta = 4
59 * Note the FIPS 204 code uses the range -4..4 (whereas this code adds q to the
60 * negative numbers).
61 *
62 * @param nibble A value in the range 0..15
63 * @param out The returned value if the range (q-4)..0..4 if nibble is < 9
64 * @returns 1 nibble was in range, or 0 if the nibble was rejected.
65 */
coeff_from_nibble_4(uint32_t nibble,uint32_t * out)66 static ossl_inline int coeff_from_nibble_4(uint32_t nibble, uint32_t *out)
67 {
68 /*
69 * This is not constant time but will not leak any important info since
70 * the value is either chosen or thrown away.
71 */
72 if (value_barrier_32(nibble < 9)) {
73 *out = mod_sub(4, nibble);
74 return 1;
75 }
76 return 0;
77 }
78
79 /**
80 * @brief Generate a value in the range (q-2..0..2)
81 * See FIPS 204, Algorithm 15, CoeffFromHalfByte() where eta = 2
82 * Note the FIPS 204 code uses the range -2..2 (whereas this code adds q to the
83 * negative numbers).
84 *
85 * @param nibble A value in the range 0..15
86 * @param out The returned value if the range (q-2)..0..2 if nibble is < 15
87 * @returns 1 nibble was in range, or 0 if the nibble was rejected.
88 */
coeff_from_nibble_2(uint32_t nibble,uint32_t * out)89 static ossl_inline int coeff_from_nibble_2(uint32_t nibble, uint32_t *out)
90 {
91 if (value_barrier_32(nibble < 15)) {
92 *out = mod_sub(2, MOD5(nibble));
93 return 1;
94 }
95 return 0;
96 }
97
98 /**
99 * @brief Use a seed value to generate a polynomial with coefficients in the
100 * range of 0..q-1 using rejection sampling.
101 * SHAKE128 is used to absorb the seed, and then sequences of 3 sample bytes are
102 * squeezed to try to produce coefficients.
103 * The SHAKE128 stream is used to get uniformly distributed elements.
104 * This algorithm is used for matrix expansion and only operates on public inputs.
105 *
106 * See FIPS 204, Algorithm 30, RejNTTPoly()
107 *
108 * @param g_ctx A EVP_MD_CTX object used for sampling the seed.
109 * @param md A pre-fetched SHAKE128 object.
110 * @param seed The seed to use for sampling.
111 * @param seed_len The size of |seed|
112 * @param out The returned polynomial with coefficients in the range of
113 * 0..q-1. This range is required for NTT.
114 * @returns 1 if the polynomial was successfully generated, or 0 if any of the
115 * digest operations failed.
116 */
rej_ntt_poly(EVP_MD_CTX * g_ctx,const EVP_MD * md,const uint8_t * seed,size_t seed_len,POLY * out)117 static int rej_ntt_poly(EVP_MD_CTX *g_ctx, const EVP_MD *md,
118 const uint8_t *seed, size_t seed_len, POLY *out)
119 {
120 int j = 0;
121 uint8_t blocks[SHAKE128_BLOCKSIZE], *b, *end = blocks + sizeof(blocks);
122
123 /*
124 * Instead of just squeezing 3 bytes at a time, we grab a whole block
125 * Note that the shake128 blocksize of 168 is divisible by 3.
126 */
127 if (!shake_xof(g_ctx, md, seed, seed_len, blocks, sizeof(blocks)))
128 return 0;
129
130 while (1) {
131 for (b = blocks; b < end; b += 3) {
132 if (coeff_from_three_bytes(b, &(out->coeff[j]))) {
133 if (++j >= ML_DSA_NUM_POLY_COEFFICIENTS)
134 return 1; /* finished */
135 }
136 }
137 if (!EVP_DigestSqueeze(g_ctx, blocks, sizeof(blocks)))
138 return 0;
139 }
140 }
141
142 /**
143 * @brief Use a seed value to generate a polynomial with coefficients in the
144 * range of ((q-eta)..0..eta) using rejection sampling. eta is either 2 or 4.
145 * SHAKE256 is used to absorb the seed, and then samples are squeezed.
146 * See FIPS 204, Algorithm 31, RejBoundedPoly()
147 *
148 * @param h_ctx A EVP_MD_CTX object context used to sample the seed.
149 * @param md A pre-fetched SHAKE256 object.
150 * @param coef_from_nibble A function that is dependent on eta, which takes a
151 * nibble and tries to see if it is in the correct range.
152 * @param seed The seed to use for sampling.
153 * @param seed_len The size of |seed|
154 * @param out The returned polynomial with coefficients in the range of
155 * ((q-eta)..0..eta)
156 * @returns 1 if the polynomial was successfully generated, or 0 if any of the
157 * digest operations failed.
158 */
rej_bounded_poly(EVP_MD_CTX * h_ctx,const EVP_MD * md,COEFF_FROM_NIBBLE_FUNC * coef_from_nibble,const uint8_t * seed,size_t seed_len,POLY * out)159 static int rej_bounded_poly(EVP_MD_CTX *h_ctx, const EVP_MD *md,
160 COEFF_FROM_NIBBLE_FUNC *coef_from_nibble,
161 const uint8_t *seed, size_t seed_len, POLY *out)
162 {
163 int ret = 0;
164 int j = 0;
165 uint32_t z0, z1;
166 uint8_t blocks[SHAKE256_BLOCKSIZE], *b, *end = blocks + sizeof(blocks);
167
168 /* Instead of just squeezing 1 byte at a time, we grab a whole block */
169 if (!shake_xof(h_ctx, md, seed, seed_len, blocks, sizeof(blocks)))
170 goto err;
171
172 while (1) {
173 for (b = blocks; b < end; b++) {
174 z0 = *b & 0x0F; /* lower nibble of byte */
175 z1 = *b >> 4; /* high nibble of byte */
176
177 if (coef_from_nibble(z0, &out->coeff[j])
178 && ++j >= ML_DSA_NUM_POLY_COEFFICIENTS) {
179 ret = 1;
180 goto err;
181 }
182 if (coef_from_nibble(z1, &out->coeff[j])
183 && ++j >= ML_DSA_NUM_POLY_COEFFICIENTS) {
184 ret = 1;
185 goto err;
186 }
187 }
188 if (!EVP_DigestSqueeze(h_ctx, blocks, sizeof(blocks)))
189 goto err;
190 }
191 err:
192 OPENSSL_cleanse(blocks, sizeof(blocks));
193 return ret;
194 }
195
196 /**
197 * @brief Generate a k * l matrix that has uniformly distributed polynomial
198 * elements using rejection sampling.
199 * See FIPS 204, Algorithm 32, ExpandA()
200 *
201 * @param g_ctx A EVP_MD_CTX context used for rejection sampling
202 * seed values generated from the seed rho.
203 * @param md A pre-fetched SHAKE128 object
204 * @param rho A 32 byte seed to generated the matrix from.
205 * @param out The generated k * l matrix of polynomials with coefficients
206 * in the range of 0..q-1.
207 * @returns 1 if the matrix was generated, or 0 on error.
208 */
ossl_ml_dsa_matrix_expand_A(EVP_MD_CTX * g_ctx,const EVP_MD * md,const uint8_t * rho,MATRIX * out)209 int ossl_ml_dsa_matrix_expand_A(EVP_MD_CTX *g_ctx, const EVP_MD *md,
210 const uint8_t *rho, MATRIX *out)
211 {
212 int ret = 0;
213 size_t i, j;
214 uint8_t derived_seed[ML_DSA_RHO_BYTES + 2];
215 POLY *poly = out->m_poly;
216
217 /*
218 * The seeds derived below and the sampling buffers in rej_ntt_poly() are
219 * not cleansed: per FIPS 204 section 3.6.3 the matrix A is easily
220 * computed from the public key and does not require any special
221 * protections.
222 */
223
224 /* The seed used for each matrix element is rho + column_index + row_index */
225 memcpy(derived_seed, rho, ML_DSA_RHO_BYTES);
226
227 for (i = 0; i < out->k; i++) {
228 for (j = 0; j < out->l; j++) {
229 derived_seed[ML_DSA_RHO_BYTES + 1] = (uint8_t)i;
230 derived_seed[ML_DSA_RHO_BYTES] = (uint8_t)j;
231 /* Generate the polynomial for each matrix element using a unique seed */
232 if (!rej_ntt_poly(g_ctx, md, derived_seed, sizeof(derived_seed), poly++))
233 goto err;
234 }
235 }
236 ret = 1;
237 err:
238 return ret;
239 }
240
241 /**
242 * @brief Generates 2 vectors using rejection sampling whose polynomial
243 * coefficients are in the interval [q-eta..0..eta]
244 *
245 * See FIPS 204, Algorithm 33, ExpandS().
246 * Note that in FIPS 204 the range -eta..eta is used.
247 *
248 * @param h_ctx A EVP_MD_CTX context to use to sample the seed.
249 * @param md A pre-fetched SHAKE256 object.
250 * @param eta Is either 2 or 4, and determines the range of the coefficients for
251 * s1 and s2.
252 * @param seed A 64 byte seed to use for sampling.
253 * @param s1 A 1 * l column vector containing polynomials with coefficients in
254 * the range (q-eta)..0..eta
255 * @param s2 A 1 * k column vector containing polynomials with coefficients in
256 * the range (q-eta)..0..eta
257 * @returns 1 if s1 and s2 were successfully generated, or 0 otherwise.
258 */
ossl_ml_dsa_vector_expand_S(EVP_MD_CTX * h_ctx,const EVP_MD * md,int eta,const uint8_t * seed,VECTOR * s1,VECTOR * s2)259 int ossl_ml_dsa_vector_expand_S(EVP_MD_CTX *h_ctx, const EVP_MD *md, int eta,
260 const uint8_t *seed, VECTOR *s1, VECTOR *s2)
261 {
262 int ret = 0;
263 size_t i;
264 size_t l = s1->num_poly;
265 size_t k = s2->num_poly;
266 uint8_t derived_seed[ML_DSA_PRIV_SEED_BYTES + 2];
267 COEFF_FROM_NIBBLE_FUNC *coef_from_nibble_fn;
268
269 coef_from_nibble_fn = (eta == ML_DSA_ETA_4) ? coeff_from_nibble_4 : coeff_from_nibble_2;
270
271 /*
272 * Each polynomial generated uses a unique seed that consists of
273 * seed + counter (where the counter is 2 bytes starting at 0)
274 */
275 memcpy(derived_seed, seed, ML_DSA_PRIV_SEED_BYTES);
276 derived_seed[ML_DSA_PRIV_SEED_BYTES] = 0;
277 derived_seed[ML_DSA_PRIV_SEED_BYTES + 1] = 0;
278
279 for (i = 0; i < l; i++) {
280 if (!rej_bounded_poly(h_ctx, md, coef_from_nibble_fn,
281 derived_seed, sizeof(derived_seed), &s1->poly[i]))
282 goto err;
283 ++derived_seed[ML_DSA_PRIV_SEED_BYTES];
284 }
285 for (i = 0; i < k; i++) {
286 if (!rej_bounded_poly(h_ctx, md, coef_from_nibble_fn,
287 derived_seed, sizeof(derived_seed), &s2->poly[i]))
288 goto err;
289 ++derived_seed[ML_DSA_PRIV_SEED_BYTES];
290 }
291 ret = 1;
292 err:
293 OPENSSL_cleanse(derived_seed, sizeof(derived_seed));
294 return ret;
295 }
296
297 /* See FIPS 204, Algorithm 34, ExpandMask(), Step 4 & 5 */
ossl_ml_dsa_poly_expand_mask(POLY * out,const uint8_t * seed,size_t seed_len,uint32_t gamma1,EVP_MD_CTX * h_ctx,const EVP_MD * md)298 int ossl_ml_dsa_poly_expand_mask(POLY *out, const uint8_t *seed, size_t seed_len,
299 uint32_t gamma1,
300 EVP_MD_CTX *h_ctx, const EVP_MD *md)
301 {
302 uint8_t buf[32 * 20];
303 size_t buf_len = 32 * (gamma1 == ML_DSA_GAMMA1_TWO_POWER_19 ? 20 : 18);
304 int ret = shake_xof(h_ctx, md, seed, seed_len, buf, buf_len)
305 && ossl_ml_dsa_poly_decode_expand_mask(out, buf, buf_len, gamma1);
306
307 OPENSSL_cleanse(buf, sizeof(buf));
308 return ret;
309 }
310
311 /*
312 * @brief Sample a polynomial with coefficients in the range {-1..1}.
313 * The number of non zero values (hamming weight) is given by tau
314 *
315 * See FIPS 204, Algorithm 29, SampleInBall()
316 * This function is assumed to not be constant time.
317 * The algorithm is based on Durstenfeld's version of the Fisher-Yates shuffle.
318 *
319 * Note that the coefficients returned by this implementation are positive
320 * i.e one of q-1, 0, or 1.
321 *
322 * @param tau is the number of +1 or -1's in the polynomial 'out_c' (39, 49 or 60)
323 * that is less than or equal to 64
324 */
ossl_ml_dsa_poly_sample_in_ball(POLY * out_c,const uint8_t * seed,int seed_len,EVP_MD_CTX * h_ctx,const EVP_MD * md,uint32_t tau)325 int ossl_ml_dsa_poly_sample_in_ball(POLY *out_c, const uint8_t *seed, int seed_len,
326 EVP_MD_CTX *h_ctx, const EVP_MD *md,
327 uint32_t tau)
328 {
329 uint8_t block[SHAKE256_BLOCKSIZE];
330 uint64_t signs;
331 int offset = 8;
332 size_t end;
333 int ret = 0;
334
335 /*
336 * Rather than squeeze 8 bytes followed by lots of 1 byte squeezes
337 * the SHAKE blocksize is squeezed each time and buffered into 'block'.
338 */
339 if (!shake_xof(h_ctx, md, seed, seed_len, block, sizeof(block)))
340 goto err;
341
342 /*
343 * grab the first 64 bits - since tau < 64
344 * Each bit gives a +1 or -1 value.
345 */
346 OPENSSL_load_u64_le(&signs, block);
347
348 poly_zero(out_c);
349
350 /* Loop tau times */
351 for (end = 256 - tau; end < 256; end++) {
352 size_t index; /* index is a random offset to write +1 or -1 */
353
354 /* rejection sample in {0..end} to choose an index to place -1 or 1 into */
355 for (;;) {
356 if (offset == sizeof(block)) {
357 /* squeeze another block if the bytes from block have been used */
358 if (!EVP_DigestSqueeze(h_ctx, block, sizeof(block)))
359 goto err;
360 offset = 0;
361 }
362
363 index = block[offset++];
364 if (index <= end)
365 break;
366 }
367
368 /*
369 * In-place swap the coefficient we are about to replace to the end so
370 * we don't lose any values that have been already written.
371 */
372 out_c->coeff[end] = out_c->coeff[index];
373 /* set the random coefficient value to either 1 or q-1 */
374 out_c->coeff[index] = mod_sub(1, 2 * (signs & 1));
375 signs >>= 1; /* grab the next random bit */
376 }
377 ret = 1;
378 err:
379 OPENSSL_cleanse(block, sizeof(block));
380 return ret;
381 }
382