xref: /third_party/mbedtls/library/bignum_mod.h (revision a8e1175b)
1/**
2 *  Modular bignum functions
3 *
4 * This module implements operations on integers modulo some fixed modulus.
5 *
6 * The functions in this module obey the following conventions unless
7 * explicitly indicated otherwise:
8 *
9 * - **Modulus parameters**: the modulus is passed as a pointer to a structure
10 *   of type #mbedtls_mpi_mod_modulus. The structure must be set up with an
11 *   array of limbs storing the bignum value of the modulus. The modulus must
12 *   be odd and is assumed to have no leading zeroes. The modulus is usually
13 *   named \c N and is usually input-only. Functions which take a parameter
14 *   of type \c const #mbedtls_mpi_mod_modulus* must not modify its value.
15 * - **Bignum parameters**: Bignums are passed as pointers to an array of
16 *   limbs or to a #mbedtls_mpi_mod_residue structure. A limb has the type
17 *   #mbedtls_mpi_uint. Residues must be initialized before use, and must be
18 *   associated with the modulus \c N. Unless otherwise specified:
19 *     - Bignum parameters called \c A, \c B, ... are inputs and are not
20 *       modified by the function. Functions which take a parameter of
21 *       type \c const #mbedtls_mpi_mod_residue* must not modify its value.
22 *     - Bignum parameters called \c X, \c Y, ... are outputs or input-output.
23 *       The initial bignum value of output-only parameters is ignored, but
24 *       they must be set up and associated with the modulus \c N. Some
25 *       functions (typically constant-flow) require that the limbs in an
26 *       output residue are initialized.
27 *     - Bignum parameters called \c p are inputs used to set up a modulus or
28 *       residue. These must be pointers to an array of limbs.
29 *     - \c T is a temporary storage area. The initial content of such a
30 *       parameter is ignored and the final content is unspecified.
31 *     - Some functions use different names, such as \c r for the residue.
32 * - **Bignum sizes**: bignum sizes are always expressed in limbs. Both
33 *   #mbedtls_mpi_mod_modulus and #mbedtls_mpi_mod_residue have a \c limbs
34 *   member storing its size. All bignum parameters must have the same
35 *   number of limbs as the modulus. All bignum sizes must be at least 1 and
36 *   must be significantly less than #SIZE_MAX. The behavior if a size is 0 is
37 *   undefined.
38 * - **Bignum representation**: the representation of inputs and outputs is
39 *   specified by the \c int_rep field of the modulus.
40 * - **Parameter ordering**: for bignum parameters, outputs come before inputs.
41 *   The modulus is passed after residues. Temporaries come last.
42 * - **Aliasing**: in general, output bignums may be aliased to one or more
43 *   inputs. Modulus values may not be aliased to any other parameter. Outputs
44 *   may not be aliased to one another. Temporaries may not be aliased to any
45 *   other parameter.
46 * - **Overlap**: apart from aliasing of residue pointers (where two residue
47 *   arguments are equal pointers), overlap is not supported and may result
48 *   in undefined behavior.
49 * - **Error handling**: functions generally check compatibility of input
50 *   sizes. Most functions will not check that input values are in canonical
51 *   form (i.e. that \c A < \c N), this is only checked during setup of a
52 *   residue structure.
53 * - **Modular representatives**: all functions expect inputs to be in the
54 *   range [0, \c N - 1] and guarantee outputs in the range [0, \c N - 1].
55 *   Residues are set up with an associated modulus, and operations are only
56 *   guaranteed to work if the modulus is associated with all residue
57 *   parameters. If a residue is passed with a modulus other than the one it
58 *   is associated with, then it may be out of range. If an input is out of
59 *   range, outputs are fully unspecified, though bignum values out of range
60 *   should not cause buffer overflows (beware that this is not extensively
61 *   tested).
62 */
63
64/*
65 *  Copyright The Mbed TLS Contributors
66 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
67 */
68
69#ifndef MBEDTLS_BIGNUM_MOD_H
70#define MBEDTLS_BIGNUM_MOD_H
71
72#include "common.h"
73
74#if defined(MBEDTLS_BIGNUM_C)
75#include "mbedtls/bignum.h"
76#endif
77
78/** How residues associated with a modulus are represented.
79 *
80 * This also determines which fields of the modulus structure are valid and
81 * what their contents are (see #mbedtls_mpi_mod_modulus).
82 */
83typedef enum {
84    /** Representation not chosen (makes the modulus structure invalid). */
85    MBEDTLS_MPI_MOD_REP_INVALID    = 0,
86    /* Skip 1 as it is slightly easier to accidentally pass to functions. */
87    /** Montgomery representation. */
88    MBEDTLS_MPI_MOD_REP_MONTGOMERY = 2,
89    /* Optimised reduction available. This indicates a coordinate modulus (P)
90     * and one or more of the following have been configured:
91     * - A nist curve (MBEDTLS_ECP_DP_SECPXXXR1_ENABLED) & MBEDTLS_ECP_NIST_OPTIM.
92     * - A Kobliz Curve.
93     * - A Fast Reduction Curve CURVE25519 or CURVE448. */
94    MBEDTLS_MPI_MOD_REP_OPT_RED,
95} mbedtls_mpi_mod_rep_selector;
96
97/* Make mbedtls_mpi_mod_rep_selector and mbedtls_mpi_mod_ext_rep disjoint to
98 * make it easier to catch when they are accidentally swapped. */
99typedef enum {
100    MBEDTLS_MPI_MOD_EXT_REP_INVALID = 0,
101    MBEDTLS_MPI_MOD_EXT_REP_LE      = 8,
102    MBEDTLS_MPI_MOD_EXT_REP_BE
103} mbedtls_mpi_mod_ext_rep;
104
105typedef struct {
106    mbedtls_mpi_uint *p;
107    size_t limbs;
108} mbedtls_mpi_mod_residue;
109
110typedef struct {
111    mbedtls_mpi_uint const *rr;  /* The residue for 2^{2*n*biL} mod N */
112    mbedtls_mpi_uint mm;         /* Montgomery const for -N^{-1} mod 2^{ciL} */
113} mbedtls_mpi_mont_struct;
114
115typedef int (*mbedtls_mpi_modp_fn)(mbedtls_mpi_uint *X, size_t X_limbs);
116
117typedef struct {
118    mbedtls_mpi_modp_fn modp;    /* The optimised reduction function pointer */
119} mbedtls_mpi_opt_red_struct;
120
121typedef struct {
122    const mbedtls_mpi_uint *p;
123    size_t limbs;                            // number of limbs
124    size_t bits;                             // bitlen of p
125    mbedtls_mpi_mod_rep_selector int_rep;    // selector to signal the active member of the union
126    union rep {
127        /* if int_rep == #MBEDTLS_MPI_MOD_REP_MONTGOMERY */
128        mbedtls_mpi_mont_struct mont;
129        /* if int_rep == #MBEDTLS_MPI_MOD_REP_OPT_RED */
130        mbedtls_mpi_opt_red_struct ored;
131    } rep;
132} mbedtls_mpi_mod_modulus;
133
134/** Setup a residue structure.
135 *
136 * The residue will be set up with the buffer \p p and modulus \p N.
137 *
138 * The memory pointed to by \p p will be used by the resulting residue structure.
139 * The value at the pointed-to memory will be the initial value of \p r and must
140 * hold a value that is less than the modulus. This value will be used as-is
141 * and interpreted according to the value of the `N->int_rep` field.
142 *
143 * The modulus \p N will be the modulus associated with \p r. The residue \p r
144 * should only be used in operations where the modulus is \p N.
145 *
146 * \param[out] r    The address of the residue to setup.
147 * \param[in] N     The address of the modulus related to \p r.
148 * \param[in] p     The address of the limb array containing the value of \p r.
149 *                  The memory pointed to by \p p will be used by \p r and must
150 *                  not be modified in any way until after
151 *                  mbedtls_mpi_mod_residue_release() is called. The data
152 *                  pointed to by \p p must be less than the modulus (the value
153 *                  pointed to by `N->p`) and already in the representation
154 *                  indicated by `N->int_rep`.
155 * \param p_limbs   The number of limbs of \p p. Must be the same as the number
156 *                  of limbs in the modulus \p N.
157 *
158 * \return      \c 0 if successful.
159 * \return      #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p p_limbs is less than the
160 *              limbs in \p N or if \p p is not less than \p N.
161 */
162int mbedtls_mpi_mod_residue_setup(mbedtls_mpi_mod_residue *r,
163                                  const mbedtls_mpi_mod_modulus *N,
164                                  mbedtls_mpi_uint *p,
165                                  size_t p_limbs);
166
167/** Unbind elements of a residue structure.
168 *
169 * This function removes the reference to the limb array that was passed to
170 * mbedtls_mpi_mod_residue_setup() to make it safe to free or use again.
171 *
172 * This function invalidates \p r and it must not be used until after
173 * mbedtls_mpi_mod_residue_setup() is called on it again.
174 *
175 * \param[out] r     The address of residue to release.
176 */
177void mbedtls_mpi_mod_residue_release(mbedtls_mpi_mod_residue *r);
178
179/** Initialize a modulus structure.
180 *
181 * \param[out] N     The address of the modulus structure to initialize.
182 */
183void mbedtls_mpi_mod_modulus_init(mbedtls_mpi_mod_modulus *N);
184
185/** Setup a modulus structure.
186 *
187 * \param[out] N    The address of the modulus structure to populate.
188 * \param[in] p     The address of the limb array storing the value of \p N.
189 *                  The memory pointed to by \p p will be used by \p N and must
190 *                  not be modified in any way until after
191 *                  mbedtls_mpi_mod_modulus_free() is called.
192 * \param p_limbs   The number of limbs of \p p.
193 *
194 * \return      \c 0 if successful.
195 */
196int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *N,
197                                  const mbedtls_mpi_uint *p,
198                                  size_t p_limbs);
199
200/** Setup an optimised-reduction compatible modulus structure.
201 *
202 * \param[out] N    The address of the modulus structure to populate.
203 * \param[in] p     The address of the limb array storing the value of \p N.
204 *                  The memory pointed to by \p p will be used by \p N and must
205 *                  not be modified in any way until after
206 *                  mbedtls_mpi_mod_modulus_free() is called.
207 * \param p_limbs   The number of limbs of \p p.
208 * \param modp      A pointer to the optimised reduction function to use. \p p.
209 *
210 * \return      \c 0 if successful.
211 */
212int mbedtls_mpi_mod_optred_modulus_setup(mbedtls_mpi_mod_modulus *N,
213                                         const mbedtls_mpi_uint *p,
214                                         size_t p_limbs,
215                                         mbedtls_mpi_modp_fn modp);
216
217/** Free elements of a modulus structure.
218 *
219 * This function frees any memory allocated by mbedtls_mpi_mod_modulus_setup().
220 *
221 * \warning This function does not free the limb array passed to
222 *          mbedtls_mpi_mod_modulus_setup() only removes the reference to it,
223 *          making it safe to free or to use it again.
224 *
225 * \param[in,out] N     The address of the modulus structure to free.
226 */
227void mbedtls_mpi_mod_modulus_free(mbedtls_mpi_mod_modulus *N);
228
229/** \brief  Multiply two residues, returning the residue modulo the specified
230 *          modulus.
231 *
232 * \note Currently handles the case when `N->int_rep` is
233 * MBEDTLS_MPI_MOD_REP_MONTGOMERY.
234 *
235 * The size of the operation is determined by \p N. \p A, \p B and \p X must
236 * all be associated with the modulus \p N and must all have the same number
237 * of limbs as \p N.
238 *
239 * \p X may be aliased to \p A or \p B, or even both, but may not overlap
240 * either otherwise. They may not alias \p N (since they must be in canonical
241 * form, they cannot == \p N).
242 *
243 * \param[out] X        The address of the result MPI. Must have the same
244 *                      number of limbs as \p N.
245 *                      On successful completion, \p X contains the result of
246 *                      the multiplication `A * B * R^-1` mod N where
247 *                      `R = 2^(biL * N->limbs)`.
248 * \param[in]  A        The address of the first MPI.
249 * \param[in]  B        The address of the second MPI.
250 * \param[in]  N        The address of the modulus. Used to perform a modulo
251 *                      operation on the result of the multiplication.
252 *
253 * \return      \c 0 if successful.
254 * \return      #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if all the parameters do not
255 *              have the same number of limbs or \p N is invalid.
256 * \return      #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
257 */
258int mbedtls_mpi_mod_mul(mbedtls_mpi_mod_residue *X,
259                        const mbedtls_mpi_mod_residue *A,
260                        const mbedtls_mpi_mod_residue *B,
261                        const mbedtls_mpi_mod_modulus *N);
262
263/**
264 * \brief Perform a fixed-size modular subtraction.
265 *
266 * Calculate `A - B modulo N`.
267 *
268 * \p A, \p B and \p X must all have the same number of limbs as \p N.
269 *
270 * \p X may be aliased to \p A or \p B, or even both, but may not overlap
271 * either otherwise.
272 *
273 * \note This function does not check that \p A or \p B are in canonical
274 *       form (that is, are < \p N) - that will have been done by
275 *       mbedtls_mpi_mod_residue_setup().
276 *
277 * \param[out] X    The address of the result MPI. Must be initialized.
278 *                  Must have the same number of limbs as the modulus \p N.
279 * \param[in]  A    The address of the first MPI.
280 * \param[in]  B    The address of the second MPI.
281 * \param[in]  N    The address of the modulus. Used to perform a modulo
282 *                  operation on the result of the subtraction.
283 *
284 * \return          \c 0 if successful.
285 * \return          #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
286 *                  have the correct number of limbs.
287 */
288int mbedtls_mpi_mod_sub(mbedtls_mpi_mod_residue *X,
289                        const mbedtls_mpi_mod_residue *A,
290                        const mbedtls_mpi_mod_residue *B,
291                        const mbedtls_mpi_mod_modulus *N);
292
293/**
294 * \brief Perform modular inversion of an MPI with respect to a modulus \p N.
295 *
296 * \p A and \p X must be associated with the modulus \p N and will therefore
297 * have the same number of limbs as \p N.
298 *
299 * \p X may be aliased to \p A.
300 *
301 * \warning  Currently only supports prime moduli, but does not check for them.
302 *
303 * \param[out] X   The modular inverse of \p A with respect to \p N.
304 * \param[in] A    The number to calculate the modular inverse of.
305 *                 Must not be 0.
306 * \param[in] N    The modulus to use.
307 *
308 * \return         \c 0 if successful.
309 * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A and \p N do not
310 *                 have the same number of limbs.
311 * \return         #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p A is zero.
312 * \return         #MBEDTLS_ERR_MPI_ALLOC_FAILED if couldn't allocate enough
313 *                 memory (needed for conversion to and from Mongtomery form
314 *                 when not in Montgomery form already, and for temporary use
315 *                 by the inversion calculation itself).
316 */
317
318int mbedtls_mpi_mod_inv(mbedtls_mpi_mod_residue *X,
319                        const mbedtls_mpi_mod_residue *A,
320                        const mbedtls_mpi_mod_modulus *N);
321/**
322 * \brief Perform a fixed-size modular addition.
323 *
324 * Calculate `A + B modulo N`.
325 *
326 * \p A, \p B and \p X must all be associated with the modulus \p N and must
327 * all have the same number of limbs as \p N.
328 *
329 * \p X may be aliased to \p A or \p B, or even both, but may not overlap
330 * either otherwise.
331 *
332 * \note This function does not check that \p A or \p B are in canonical
333 *       form (that is, are < \p N) - that will have been done by
334 *       mbedtls_mpi_mod_residue_setup().
335 *
336 * \param[out] X    The address of the result residue. Must be initialized.
337 *                  Must have the same number of limbs as the modulus \p N.
338 * \param[in]  A    The address of the first input residue.
339 * \param[in]  B    The address of the second input residue.
340 * \param[in]  N    The address of the modulus. Used to perform a modulo
341 *                  operation on the result of the addition.
342 *
343 * \return          \c 0 if successful.
344 * \return          #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the given MPIs do not
345 *                  have the correct number of limbs.
346 */
347int mbedtls_mpi_mod_add(mbedtls_mpi_mod_residue *X,
348                        const mbedtls_mpi_mod_residue *A,
349                        const mbedtls_mpi_mod_residue *B,
350                        const mbedtls_mpi_mod_modulus *N);
351
352/** Generate a random number uniformly in a range.
353 *
354 * This function generates a random number between \p min inclusive and
355 * \p N exclusive.
356 *
357 * The procedure complies with RFC 6979 §3.3 (deterministic ECDSA)
358 * when the RNG is a suitably parametrized instance of HMAC_DRBG
359 * and \p min is \c 1.
360 *
361 * \note           There are `N - min` possible outputs. The lower bound
362 *                 \p min can be reached, but the upper bound \p N cannot.
363 *
364 * \param X        The destination residue.
365 * \param min      The minimum value to return. It must be strictly smaller
366 *                 than \b N.
367 * \param N        The modulus.
368 *                 This is the upper bound of the output range, exclusive.
369 * \param f_rng    The RNG function to use. This must not be \c NULL.
370 * \param p_rng    The RNG parameter to be passed to \p f_rng.
371 *
372 * \return         \c 0 if successful.
373 * \return         #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
374 *                 unable to find a suitable value within a limited number
375 *                 of attempts. This has a negligible probability if \p N
376 *                 is significantly larger than \p min, which is the case
377 *                 for all usual cryptographic applications.
378 */
379int mbedtls_mpi_mod_random(mbedtls_mpi_mod_residue *X,
380                           mbedtls_mpi_uint min,
381                           const mbedtls_mpi_mod_modulus *N,
382                           int (*f_rng)(void *, unsigned char *, size_t),
383                           void *p_rng);
384
385/** Read a residue from a byte buffer.
386 *
387 * The residue will be automatically converted to the internal representation
388 * based on the value of the `N->int_rep` field.
389 *
390 * The modulus \p N will be the modulus associated with \p r. The residue \p r
391 * should only be used in operations where the modulus is \p N or a modulus
392 * equivalent to \p N (in the sense that all their fields or memory pointed by
393 * their fields hold the same value).
394 *
395 * \param[out] r    The address of the residue. It must have exactly the same
396 *                  number of limbs as the modulus \p N.
397 * \param[in] N     The address of the modulus.
398 * \param[in] buf   The input buffer to import from.
399 * \param buflen    The length in bytes of \p buf.
400 * \param ext_rep   The endianness of the number in the input buffer.
401 *
402 * \return       \c 0 if successful.
403 * \return       #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p r isn't
404 *               large enough to hold the value in \p buf.
405 * \return       #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p ext_rep
406 *               is invalid or the value in the buffer is not less than \p N.
407 */
408int mbedtls_mpi_mod_read(mbedtls_mpi_mod_residue *r,
409                         const mbedtls_mpi_mod_modulus *N,
410                         const unsigned char *buf,
411                         size_t buflen,
412                         mbedtls_mpi_mod_ext_rep ext_rep);
413
414/** Write a residue into a byte buffer.
415 *
416 * The modulus \p N must be the modulus associated with \p r (see
417 * mbedtls_mpi_mod_residue_setup() and mbedtls_mpi_mod_read()).
418 *
419 * The residue will be automatically converted from the internal representation
420 * based on the value of `N->int_rep` field.
421 *
422 * \warning     If the buffer is smaller than `N->bits`, the number of
423 *              leading zeroes is leaked through timing. If \p r is
424 *              secret, the caller must ensure that \p buflen is at least
425 *              (`N->bits`+7)/8.
426 *
427 * \param[in] r     The address of the residue. It must have the same number of
428 *                  limbs as the modulus \p N. (\p r is an input parameter, but
429 *                  its value will be modified during execution and restored
430 *                  before the function returns.)
431 * \param[in] N     The address of the modulus associated with \p r.
432 * \param[out] buf  The output buffer to export to.
433 * \param buflen    The length in bytes of \p buf.
434 * \param ext_rep   The endianness in which the number should be written into
435 *                  the output buffer.
436 *
437 * \return       \c 0 if successful.
438 * \return       #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
439 *               large enough to hold the value of \p r (without leading
440 *               zeroes).
441 * \return       #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p ext_rep is invalid.
442 * \return       #MBEDTLS_ERR_MPI_ALLOC_FAILED if couldn't allocate enough
443 *               memory for conversion. Can occur only for moduli with
444 *               MBEDTLS_MPI_MOD_REP_MONTGOMERY.
445 */
446int mbedtls_mpi_mod_write(const mbedtls_mpi_mod_residue *r,
447                          const mbedtls_mpi_mod_modulus *N,
448                          unsigned char *buf,
449                          size_t buflen,
450                          mbedtls_mpi_mod_ext_rep ext_rep);
451
452#endif /* MBEDTLS_BIGNUM_MOD_H */
453