Coverage Report

Created: 2026-10-19 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/fipsmodule/bn/internal.h
Line
Count
Source
1
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2
// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
3
//
4
// Licensed under the Apache License, Version 2.0 (the "License");
5
// you may not use this file except in compliance with the License.
6
// You may obtain a copy of the License at
7
//
8
//     https://www.apache.org/licenses/LICENSE-2.0
9
//
10
// Unless required by applicable law or agreed to in writing, software
11
// distributed under the License is distributed on an "AS IS" BASIS,
12
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
// See the License for the specific language governing permissions and
14
// limitations under the License.
15
16
#ifndef OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_INTERNAL_H
17
#define OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_INTERNAL_H
18
19
#include <openssl/bn.h>
20
21
#if defined(OPENSSL_X86_64) && defined(_MSC_VER)
22
#include <intrin.h>
23
#pragma intrinsic(__umulh, _umul128)
24
#endif
25
26
#include "../../internal.h"
27
28
29
BSSL_NAMESPACE_BEGIN
30
31
#if defined(OPENSSL_64_BIT)
32
33
#if defined(BORINGSSL_HAS_UINT128)
34
// MSVC doesn't support two-word integers on 64-bit.
35
28.6M
#define BN_ULLONG uint128_t
36
#if defined(BORINGSSL_CAN_DIVIDE_UINT128)
37
#define BN_CAN_DIVIDE_ULLONG
38
#endif
39
#endif
40
41
327M
#define BN_BITS2 64
42
47.0k
#define BN_BITS2_LG 6
43
373k
#define BN_BYTES 8
44
#define BN_BITS4 32
45
107k
#define BN_MASK2 (0xffffffffffffffffUL)
46
#define BN_MASK2l (0xffffffffUL)
47
#define BN_MASK2h (0xffffffff00000000UL)
48
#define BN_MASK2h1 (0xffffffff80000000UL)
49
0
#define BN_MONT_CTX_N0_LIMBS 1
50
18.8k
#define BN_DEC_CONV (10000000000000000000UL)
51
206k
#define BN_DEC_NUM 19
52
0
#define TOBN(hi, lo) ((BN_ULONG)(hi) << 32 | (lo))
53
54
#elif defined(OPENSSL_32_BIT)
55
56
#define BN_ULLONG uint64_t
57
#define BN_CAN_DIVIDE_ULLONG
58
#define BN_BITS2 32
59
#define BN_BITS2_LG 5
60
#define BN_BYTES 4
61
#define BN_BITS4 16
62
#define BN_MASK2 (0xffffffffUL)
63
#define BN_MASK2l (0xffffUL)
64
#define BN_MASK2h1 (0xffff8000UL)
65
#define BN_MASK2h (0xffff0000UL)
66
// On some 32-bit platforms, Montgomery multiplication is done using 64-bit
67
// arithmetic with SIMD instructions. On such platforms, `BN_MONT_CTX::n0`
68
// needs to be two words long. Only certain 32-bit platforms actually make use
69
// of n0[1] and shorter R value would suffice for the others. However,
70
// currently only the assembly files know which is which.
71
#define BN_MONT_CTX_N0_LIMBS 2
72
#define BN_DEC_CONV (1000000000UL)
73
#define BN_DEC_NUM 9
74
#define TOBN(hi, lo) (lo), (hi)
75
76
#else
77
#error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT"
78
#endif
79
80
#if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
81
#define BN_CAN_USE_INLINE_ASM
82
#endif
83
84
// MOD_EXP_CTIME_ALIGN is the alignment needed for `BN_mod_exp_mont_consttime`'s
85
// tables.
86
//
87
// TODO(davidben): Historically, this alignment came from cache line
88
// assumptions, which we've since removed. Is 64-byte alignment still necessary
89
// or ideal? The true alignment requirement seems to now be 32 bytes, coming
90
// from RSAZ's use of VMOVDQA to a YMM register. Non-x86_64 has even fewer
91
// requirements.
92
138
#define MOD_EXP_CTIME_ALIGN 64
93
94
// MOD_EXP_CTIME_STORAGE_LEN is the number of `BN_ULONG`s needed for the
95
// `BN_mod_exp_mont_consttime` stack-allocated storage buffer. The buffer is
96
// just the right size for the RSAZ and is about ~1KB larger than what's
97
// necessary (4480 bytes) for 1024-bit inputs.
98
#define MOD_EXP_CTIME_STORAGE_LEN \
99
0
  (((320u * 3u) + (32u * 9u * 16u)) / sizeof(BN_ULONG))
100
101
#define STATIC_BIGNUM(x)                                    \
102
  {                                                         \
103
    (BN_ULONG *)(x), sizeof(x) / sizeof(BN_ULONG),          \
104
        sizeof(x) / sizeof(BN_ULONG), 0, BN_FLG_STATIC_DATA \
105
  }
106
107
// bn_minimal_width returns the minimal number of words needed to represent
108
// `bn`.
109
int bn_minimal_width(const BIGNUM *bn);
110
111
// bn_set_minimal_width sets `bn->width` to `bn_minimal_width(bn)`. If `bn` is
112
// zero, `bn->neg` is set to zero.
113
void bn_set_minimal_width(BIGNUM *bn);
114
115
// bn_wexpand ensures that `bn` has at least `words` works of space without
116
// altering its value. It returns one on success or zero on allocation
117
// failure.
118
int bn_wexpand(BIGNUM *bn, size_t words);
119
120
// bn_expand acts the same as `bn_wexpand`, but takes a number of bits rather
121
// than a number of words.
122
int bn_expand(BIGNUM *bn, size_t bits);
123
124
// bn_resize_words adjusts `bn->width` to be `words`. It returns one on success
125
// and zero on allocation error or if `bn`'s value is too large.
126
OPENSSL_EXPORT int bn_resize_words(BIGNUM *bn, size_t words);
127
128
// bn_select_words sets `r` to `a` if `mask` is all ones or `b` if `mask` is
129
// all zeros.
130
void bn_select_words(BN_ULONG *r, BN_ULONG mask, const BN_ULONG *a,
131
                     const BN_ULONG *b, size_t num);
132
133
// bn_set_words sets `bn` to the value encoded in the `num` words in `words`,
134
// least significant word first.
135
int bn_set_words(BIGNUM *bn, const BN_ULONG *words, size_t num);
136
137
// bn_set_static_words acts like `bn_set_words`, but doesn't copy the data. A
138
// flag is set on `bn` so that `BN_free` won't attempt to free the data.
139
//
140
// The `STATIC_BIGNUM` macro is probably a better solution for this outside of
141
// the FIPS module. Inside of the FIPS module that macro generates rel.ro data,
142
// which doesn't work with FIPS requirements.
143
void bn_set_static_words(BIGNUM *bn, const BN_ULONG *words, size_t num);
144
145
// bn_fits_in_words returns one if `bn` may be represented in `num` words, plus
146
// a sign bit, and zero otherwise.
147
int bn_fits_in_words(const BIGNUM *bn, size_t num);
148
149
// bn_copy_words copies the value of `bn` to `out` and returns one if the value
150
// is representable in `num` words. Otherwise, it returns zero.
151
int bn_copy_words(BN_ULONG *out, size_t num, const BIGNUM *bn);
152
153
// bn_assert_fits_in_bytes asserts that `bn` fits in `num` bytes. This is a
154
// no-op in release builds, but triggers an assert in debug builds, and
155
// declassifies all bytes which are therefore known to be zero in constant-time
156
// validation.
157
void bn_assert_fits_in_bytes(const BIGNUM *bn, size_t num);
158
159
// bn_secret marks `bn`'s contents, but not its width or sign, as secret. See
160
// `CONSTTIME_SECRET` for details.
161
24
inline void bn_secret(BIGNUM *bn) {
162
24
  CONSTTIME_SECRET(bn->d, bn->width * sizeof(BN_ULONG));
163
24
}
164
165
// bn_declassify marks `bn`'s value as public. See `CONSTTIME_DECLASSIFY` for
166
// details.
167
0
inline void bn_declassify(BIGNUM *bn) {
168
0
  CONSTTIME_DECLASSIFY(bn->d, bn->width * sizeof(BN_ULONG));
169
0
}
170
171
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86)
172
// See asm/bn-586.pl.
173
#define BN_ADD_ASM
174
#define BN_MUL_ASM
175
#endif
176
177
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && \
178
    (defined(__GNUC__) || defined(__clang__))
179
// See asm/x86_64-gcc.c
180
#define BN_ADD_ASM
181
#define BN_MUL_ASM
182
#endif
183
184
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_AARCH64)
185
// See asm/bn-armv8.pl.
186
#define BN_ADD_ASM
187
#endif
188
189
// bn_mul_add_words multiples `ap` by `w`, adds the result to `rp`, and places
190
// the result in `rp`. `ap` and `rp` must both be `num` words long. It returns
191
// the carry word of the operation. `ap` and `rp` may be equal but otherwise may
192
// not alias.
193
#if defined(BN_MUL_ASM)
194
extern "C"
195
#endif
196
    BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num,
197
                              BN_ULONG w);
198
199
// bn_mul_words multiples `ap` by `w` and places the result in `rp`. `ap` and
200
// `rp` must both be `num` words long. It returns the carry word of the
201
// operation. `ap` and `rp` may be equal but otherwise may not alias.
202
#if defined(BN_MUL_ASM)
203
extern "C"
204
#endif
205
    BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num,
206
                          BN_ULONG w);
207
208
// bn_sqr_add_words computes `tmp` where `tmp[2*i]` and `tmp[2*i+1]` are
209
// `ap[i]`'s square, for all `i` up to `num`, and adds the result to `rp`. If
210
// the result does not fit in `2*num` words, the final carry bit is truncated.
211
// `ap` is an array of `num` words and `rp` an array of `2*num` words. `ap` and
212
// `rp` may not alias.
213
//
214
// This gives the contribution of the `ap[i]*ap[i]` terms when squaring `ap`.
215
#if defined(BN_MUL_ASM)
216
extern "C"
217
#endif
218
    void bn_sqr_add_words(BN_ULONG *rp, const BN_ULONG *ap, size_t num);
219
220
// bn_add_words adds `ap` to `bp` and places the result in `rp`, each of which
221
// are `num` words long. It returns the carry bit, which is one if the operation
222
// overflowed and zero otherwise. Any pair of `ap`, `bp`, and `rp` may be equal
223
// to each other but otherwise may not alias.
224
#if defined(BN_ADD_ASM)
225
extern "C"
226
#endif
227
    BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
228
                          size_t num);
229
230
// bn_sub_words subtracts `bp` from `ap` and places the result in `rp`. It
231
// returns the borrow bit, which is one if the computation underflowed and zero
232
// otherwise. Any pair of `ap`, `bp`, and `rp` may be equal to each other but
233
// otherwise may not alias.
234
#if defined(BN_ADD_ASM)
235
extern "C"
236
#endif
237
    BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
238
                          size_t num);
239
240
// bn_mul_comba4 sets `r` to the product of `a` and `b`.
241
#if defined(BN_MUL_ASM)
242
extern "C"
243
#endif
244
    void bn_mul_comba4(BN_ULONG r[8], const BN_ULONG a[4], const BN_ULONG b[4]);
245
246
// bn_mul_comba8 sets `r` to the product of `a` and `b`.
247
#if defined(BN_MUL_ASM)
248
extern "C"
249
#endif
250
    void bn_mul_comba8(BN_ULONG r[16], const BN_ULONG a[8],
251
                       const BN_ULONG b[8]);
252
253
// bn_sqr_comba8 sets `r` to `a`².
254
#if defined(BN_MUL_ASM)
255
extern "C"
256
#endif
257
    void bn_sqr_comba8(BN_ULONG r[16], const BN_ULONG a[8]);
258
259
// bn_sqr_comba4 sets `r` to `a`².
260
#if defined(BN_MUL_ASM)
261
extern "C"
262
#endif
263
    void bn_sqr_comba4(BN_ULONG r[8], const BN_ULONG a[4]);
264
265
// bn_add_carry_words adds `carry` to `ap` and places the result in `rp`. `ap`
266
// and `rp` are `num` words long and may alias. `carry` must be 0 or 1. It
267
// returns the carry bit, which is one if the operation overflowed and zero
268
// otherwise.
269
BN_ULONG bn_add_carry_words(BN_ULONG *rp, const BN_ULONG *ap, BN_ULONG carry,
270
                            size_t num);
271
272
// bn_less_than_words returns one if `a` < `b` and zero otherwise, where `a`
273
// and `b` both are `len` words long. It runs in constant time.
274
int bn_less_than_words(const BN_ULONG *a, const BN_ULONG *b, size_t len);
275
276
// bn_in_range_words returns one if `min_inclusive` <= `a` < `max_exclusive`,
277
// where `a` and `max_exclusive` both are `len` words long. `a` and
278
// `max_exclusive` are treated as secret.
279
int bn_in_range_words(const BN_ULONG *a, BN_ULONG min_inclusive,
280
                      const BN_ULONG *max_exclusive, size_t len);
281
282
// bn_rand_range_words sets `out` to a uniformly distributed random number from
283
// `min_inclusive` to `max_exclusive`. Both `out` and `max_exclusive` are `len`
284
// words long.
285
//
286
// This function runs in time independent of the result, but `min_inclusive` and
287
// `max_exclusive` are public data. (Information about the range is unavoidably
288
// leaked by how many iterations it took to select a number.)
289
int bn_rand_range_words(BN_ULONG *out, BN_ULONG min_inclusive,
290
                        const BN_ULONG *max_exclusive, size_t len,
291
                        const uint8_t additional_data[32]);
292
293
// bn_range_secret_range behaves like `BN_rand_range_ex`, but treats
294
// `max_exclusive` as secret. Because of this constraint, the distribution of
295
// values returned is more complex.
296
//
297
// Rather than repeatedly generating values until one is in range, which would
298
// leak information, it generates one value. If the value is in range, it sets
299
// `*out_is_uniform` to one. Otherwise, it sets `*out_is_uniform` to zero,
300
// fixing up the value to force it in range.
301
//
302
// The subset of calls to `bn_rand_secret_range` which set `*out_is_uniform` to
303
// one are uniformly distributed in the target range. Calls overall are not.
304
// This function is intended for use in situations where the extra values are
305
// still usable and where the number of iterations needed to reach the target
306
// number of uniform outputs may be blinded for negligible probabilities of
307
// timing leaks.
308
//
309
// Although this function treats `max_exclusive` as secret, it treats the number
310
// of bits in `max_exclusive` as public.
311
int bn_rand_secret_range(BIGNUM *r, int *out_is_uniform, BN_ULONG min_inclusive,
312
                         const BIGNUM *max_exclusive);
313
314
// BN_MONTGOMERY_MAX_WORDS is the maximum number of words allowed in a `BIGNUM`
315
// used with Montgomery reduction. Ideally this limit would be applied to all
316
// `BIGNUM`s, in `bn_wexpand`, but the exactfloat library needs to create 8 MiB
317
// values for other operations.
318
//
319
// This limit is set so that one number fits within 2 KiB, giving room to
320
// allocate a few of them on the stack. It is also set to limit the DoS impact
321
// of large RSA, DH, and DSA keys, which scale cubically.
322
24.3k
#define BN_MONTGOMERY_MAX_WORDS (16384 / BN_BITS2)
323
324
BSSL_NAMESPACE_END
325
326
struct bn_mont_ctx_st {
327
  // RR is R², reduced modulo `N`. It is used to convert to Montgomery form. It
328
  // is guaranteed to have the same width as `N`.
329
  BIGNUM RR;
330
  // N is the modulus. It is always stored in minimal form, so `N.width`
331
  // determines R.
332
  BIGNUM N;
333
  BN_ULONG n0[BN_MONT_CTX_N0_LIMBS];  // least significant words of (R*Ri-1)/N
334
};
335
336
BSSL_NAMESPACE_BEGIN
337
338
#if !defined(OPENSSL_NO_ASM) &&                         \
339
    (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \
340
     defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64))
341
#define OPENSSL_BN_ASM_MONT
342
// bn_mul_mont_words writes `ap` * `bp` mod `np` to `rp`, each `num` words
343
// long. Inputs and outputs are in Montgomery form. `n0` is a pointer to the
344
// corresponding field in `BN_MONT_CTX`.
345
//
346
// If at least one of `ap` or `bp` is fully reduced, `rp` will be fully reduced.
347
// If neither is fully-reduced, the output may not be either.
348
//
349
// This function allocates up to 2 * `num` words (plus a constant allocation) on
350
// the stack, so `num` should be at most `BN_MONTGOMERY_MAX_WORDS`.
351
// Additionally, `num` must be at least 128 / `BN_BITS2`.
352
//
353
// TODO(davidben): The x86_64 implementation expects a 32-bit input and masks
354
// off upper bits. The aarch64 implementation expects a 64-bit input and does
355
// not. `size_t` is the safer option but not strictly correct for x86_64. But
356
// the `BN_MONTGOMERY_MAX_WORDS` bound makes this moot.
357
//
358
// See also discussion in `ToWord` in abi_test.h for notes on smaller-than-word
359
// inputs.
360
extern "C" void bn_mul_mont_words(BN_ULONG *rp, const BN_ULONG *ap,
361
                                  const BN_ULONG *bp, const BN_ULONG *np,
362
                                  const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
363
                                  size_t num);
364
365
#if defined(OPENSSL_X86_64)
366
1.39M
inline int bn_mulx_adx_capable() {
367
  // MULX is in BMI2.
368
1.39M
  return CRYPTO_is_BMI2_capable() && CRYPTO_is_ADX_capable();
369
1.39M
}
370
extern "C" void bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap,
371
                                 const BN_ULONG *bp, const BN_ULONG *np,
372
                                 const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
373
                                 size_t num);
374
248M
inline int bn_mul4x_mont_capable(size_t num) {
375
248M
  return num >= 8 && (num & 3) == 0;
376
248M
}
377
extern "C" void bn_mul4x_mont(BN_ULONG *rp, const BN_ULONG *ap,
378
                              const BN_ULONG *bp, const BN_ULONG *np,
379
                              const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
380
                              size_t num);
381
124M
inline int bn_mulx4x_mont_capable(size_t num) {
382
124M
  return bn_mul4x_mont_capable(num) && bn_mulx_adx_capable();
383
124M
}
384
extern "C" void bn_mulx4x_mont(BN_ULONG *rp, const BN_ULONG *ap,
385
                               const BN_ULONG *bp, const BN_ULONG *np,
386
                               const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
387
                               size_t num);
388
69.8M
inline int bn_sqr8x_mont_capable(size_t num) {
389
69.8M
  return num >= 8 && (num & 7) == 0;
390
69.8M
}
391
extern "C" void bn_sqr8x_mont(BN_ULONG *rp, const BN_ULONG *ap,
392
                              BN_ULONG mulx_adx_capable, const BN_ULONG *np,
393
                              const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
394
                              size_t num);
395
#elif defined(OPENSSL_ARM)
396
inline int bn_mul8x_mont_neon_capable(size_t num) {
397
  return (num & 7) == 0 && CRYPTO_is_NEON_capable();
398
}
399
extern "C" void bn_mul8x_mont_neon(BN_ULONG *rp, const BN_ULONG *ap,
400
                                   const BN_ULONG *bp, const BN_ULONG *np,
401
                                   const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
402
                                   size_t num);
403
extern "C" void bn_mul_mont_nohw(BN_ULONG *rp, const BN_ULONG *ap,
404
                                 const BN_ULONG *bp, const BN_ULONG *np,
405
                                 const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
406
                                 size_t num);
407
#endif
408
409
#endif  // OPENSSL_BN_ASM_MONT
410
411
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64)
412
#define OPENSSL_BN_ASM_MONT5
413
414
// The following functions implement `bn_mul_mont_gather5`. See
415
// `bn_mul_mont_gather5` for details.
416
554k
inline int bn_mul4x_mont_gather5_capable(int num) { return (num & 7) == 0; }
417
extern "C" void bn_mul4x_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
418
                                      const BN_ULONG *table, const BN_ULONG *np,
419
                                      const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
420
                                      int num, int power);
421
422
543k
inline int bn_mulx4x_mont_gather5_capable(int num) {
423
543k
  return bn_mul4x_mont_gather5_capable(num) && CRYPTO_is_ADX_capable() &&
424
531k
         CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable();
425
543k
}
426
extern "C" void bn_mulx4x_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
427
                                       const BN_ULONG *table,
428
                                       const BN_ULONG *np,
429
                                       const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS],
430
                                       int num, int power);
431
432
extern "C" void bn_mul_mont_gather5_nohw(
433
    BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, const BN_ULONG *np,
434
    const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], int num, int power);
435
436
// bn_scatter5 stores `inp` to index `power` of `table`. `inp` and each entry of
437
// `table` are `num` words long. `power` must be less than 32 and is treated as
438
// public. `table` must be 32*`num` words long. `table` must be aligned to at
439
// least 16 bytes.
440
extern "C" void bn_scatter5(const BN_ULONG *inp, size_t num, BN_ULONG *table,
441
                            size_t power);
442
443
// bn_gather5 loads index `power` of `table` and stores it in `out`. `out` and
444
// each entry of `table` are `num` words long. `power` must be less than 32 and
445
// is treated as secret. `table` must be aligned to at least 16 bytes.
446
extern "C" void bn_gather5(BN_ULONG *out, size_t num, const BN_ULONG *table,
447
                           size_t power);
448
449
// The following functions implement `bn_power5`. See `bn_power5` for details.
450
extern "C" void bn_power5_nohw(BN_ULONG *rp, const BN_ULONG *ap,
451
                               const BN_ULONG *table, const BN_ULONG *np,
452
                               const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], int num,
453
                               int power);
454
455
14.4M
inline int bn_power5_capable(int num) { return (num & 7) == 0; }
456
457
7.22M
inline int bn_powerx5_capable(int num) {
458
7.22M
  return bn_power5_capable(num) && CRYPTO_is_ADX_capable() &&
459
7.22M
         CRYPTO_is_BMI1_capable() && CRYPTO_is_BMI2_capable();
460
7.22M
}
461
extern "C" void bn_powerx5(BN_ULONG *rp, const BN_ULONG *ap,
462
                           const BN_ULONG *table, const BN_ULONG *np,
463
                           const BN_ULONG n0[BN_MONT_CTX_N0_LIMBS], int num,
464
                           int power);
465
466
#endif  // !OPENSSL_NO_ASM && OPENSSL_X86_64
467
468
uint64_t bn_mont_n0(const BIGNUM *n);
469
470
// bn_mont_ctx_set_RR_consttime initializes `mont->RR`. It returns one on
471
// success and zero on error. `mont->N` and `mont->n0` must have been
472
// initialized already. The bit width of `mont->N` is assumed public, but
473
// `mont->N` is otherwise treated as secret.
474
int bn_mont_ctx_set_RR_consttime(BN_MONT_CTX *mont, BN_CTX *ctx);
475
476
#if defined(_MSC_VER)
477
#if defined(OPENSSL_X86_64)
478
#define BN_UMULT_LOHI(low, high, a, b) ((low) = _umul128((a), (b), &(high)))
479
#elif defined(OPENSSL_AARCH64)
480
#define BN_UMULT_LOHI(low, high, a, b) \
481
  do {                                 \
482
    const BN_ULONG _a = (a);           \
483
    const BN_ULONG _b = (b);           \
484
    (low) = _a * _b;                   \
485
    (high) = __umulh(_a, _b);          \
486
  } while (0)
487
#endif
488
#endif  // _MSC_VER
489
490
#if !defined(BN_ULLONG) && !defined(BN_UMULT_LOHI)
491
#error "Either BN_ULLONG or BN_UMULT_LOHI must be defined on every platform."
492
#endif
493
494
// bn_jacobi returns the Jacobi symbol of `a` and `b` (which is -1, 0 or 1), or
495
// -2 on error.
496
int bn_jacobi(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
497
498
// bn_is_bit_set_words returns one if bit `bit` is set in `a` and zero
499
// otherwise.
500
int bn_is_bit_set_words(const BN_ULONG *a, size_t num, size_t bit);
501
502
// bn_one_to_montgomery sets `r` to one in Montgomery form. It returns one on
503
// success and zero on error. This function treats the bit width of the modulus
504
// as public.
505
int bn_one_to_montgomery(BIGNUM *r, const BN_MONT_CTX *mont, BN_CTX *ctx);
506
507
// bn_less_than_montgomery_R returns one if `bn` is less than the Montgomery R
508
// value for `mont` and zero otherwise.
509
int bn_less_than_montgomery_R(const BIGNUM *bn, const BN_MONT_CTX *mont);
510
511
// bn_mod_u16_consttime returns `bn` mod `d`, ignoring `bn`'s sign bit. It runs
512
// in time independent of the value of `bn`, but it treats `d` as public.
513
OPENSSL_EXPORT uint16_t bn_mod_u16_consttime(const BIGNUM *bn, uint16_t d);
514
515
// bn_odd_number_is_obviously_composite returns one if `bn` is divisible by one
516
// of the first several odd primes and zero otherwise.
517
int bn_odd_number_is_obviously_composite(const BIGNUM *bn);
518
519
// A BN_MILLER_RABIN stores state common to each Miller-Rabin iteration. It is
520
// initialized within an existing `BN_CTX` scope and may not be used after
521
// that scope is released with `BN_CTX_end`. Field names match those in FIPS
522
// 186-5, section B.3.1.
523
typedef struct {
524
  // w1 is w-1.
525
  BIGNUM *w1;
526
  // m is (w-1)/2^a.
527
  BIGNUM *m;
528
  // one_mont is 1 (mod w) in Montgomery form.
529
  BIGNUM *one_mont;
530
  // w1_mont is w-1 (mod w) in Montgomery form.
531
  BIGNUM *w1_mont;
532
  // w_bits is BN_num_bits(w).
533
  int w_bits;
534
  // a is the largest integer such that 2^a divides w-1.
535
  int a;
536
} BN_MILLER_RABIN;
537
538
// bn_miller_rabin_init initializes `miller_rabin` for testing if `mont->N` is
539
// prime. It returns one on success and zero on error.
540
OPENSSL_EXPORT int bn_miller_rabin_init(BN_MILLER_RABIN *miller_rabin,
541
                                        const BN_MONT_CTX *mont, BN_CTX *ctx);
542
543
// bn_miller_rabin_iteration performs one Miller-Rabin iteration, checking if
544
// `b` is a composite witness for `mont->N`. `miller_rabin` must have been
545
// initialized with `bn_miller_rabin_setup`. On success, it returns one and sets
546
// `*out_is_possibly_prime` to one if `mont->N` may still be prime or zero if
547
// `b` shows it is composite. On allocation or internal failure, it returns
548
// zero.
549
OPENSSL_EXPORT int bn_miller_rabin_iteration(
550
    const BN_MILLER_RABIN *miller_rabin, int *out_is_possibly_prime,
551
    const BIGNUM *b, const BN_MONT_CTX *mont, BN_CTX *ctx);
552
553
// bn_rshift1_words sets `r` to `a` >> 1, where both arrays are `num` bits wide.
554
void bn_rshift1_words(BN_ULONG *r, const BN_ULONG *a, size_t num);
555
556
// bn_rshift_words sets `r` to `a` >> `shift`, where both arrays are `num` bits
557
// wide.
558
void bn_rshift_words(BN_ULONG *r, const BN_ULONG *a, unsigned shift,
559
                     size_t num);
560
561
// bn_rshift_secret_shift behaves like `BN_rshift` but runs in time independent
562
// of both `a` and `n`.
563
OPENSSL_EXPORT int bn_rshift_secret_shift(BIGNUM *r, const BIGNUM *a,
564
                                          unsigned n, BN_CTX *ctx);
565
566
// bn_reduce_once sets `r` to `a` mod `m` where 0 <= `a` < 2*`m`. It returns
567
// zero if `a` < `m` and a mask of all ones if `a` >= `m`. Each array is `num`
568
// words long, but `a` has an additional word specified by `carry`. `carry` must
569
// be zero or one, as implied by the bounds on `a`.
570
//
571
// `r`, `a`, and `m` may not alias. Use `bn_reduce_once_in_place` if `r` and `a`
572
// must alias.
573
BN_ULONG bn_reduce_once(BN_ULONG *r, const BN_ULONG *a, BN_ULONG carry,
574
                        const BN_ULONG *m, size_t num);
575
576
// bn_reduce_once_in_place behaves like `bn_reduce_once` but acts in-place on
577
// `r`, using `tmp` as scratch space. `r`, `tmp`, and `m` may not alias.
578
BN_ULONG bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, const BN_ULONG *m,
579
                                 BN_ULONG *tmp, size_t num);
580
581
582
// Constant-time non-modular arithmetic.
583
//
584
// The following functions implement non-modular arithmetic in constant-time
585
// and pessimally set `r->width` to the largest possible word size.
586
//
587
// Note this means that, e.g., repeatedly multiplying by one will cause widths
588
// to increase without bound. The corresponding public API functions minimize
589
// their outputs to avoid regressing calculator consumers.
590
591
// bn_uadd_consttime behaves like `BN_uadd`, but it pessimally sets
592
// `r->width` = `a->width` + `b->width` + 1.
593
int bn_uadd_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
594
595
// bn_usub_consttime behaves like `BN_usub`, but it pessimally sets
596
// `r->width` = `a->width`.
597
int bn_usub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
598
599
// bn_abs_sub_consttime sets `r` to the absolute value of `a` - `b`, treating
600
// both inputs as secret. It returns one on success and zero on error.
601
OPENSSL_EXPORT int bn_abs_sub_consttime(BIGNUM *r, const BIGNUM *a,
602
                                        const BIGNUM *b, BN_CTX *ctx);
603
604
// bn_mul_consttime behaves like `BN_mul`, but it rejects negative inputs and
605
// pessimally sets `r->width` to `a->width` + `b->width`, to avoid leaking
606
// information about `a` and `b`.
607
int bn_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
608
609
// bn_sqrt_consttime behaves like `BN_sqrt`, but it pessimally sets `r->width`
610
// to 2*`a->width`, to avoid leaking information about `a` and `b`.
611
int bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx);
612
613
// bn_div_consttime behaves like `BN_div`, but it rejects negative inputs and
614
// treats both inputs, including their magnitudes, as secret. It is, as a
615
// result, much slower than `BN_div` and should only be used for rare operations
616
// where Montgomery reduction is not available. `divisor_min_bits` is a
617
// public lower bound for `BN_num_bits(divisor)`. When `divisor`'s bit width is
618
// public, this can speed up the operation.
619
//
620
// Note that `quotient->width` will be set pessimally to `numerator->width`.
621
OPENSSL_EXPORT int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder,
622
                                    const BIGNUM *numerator,
623
                                    const BIGNUM *divisor,
624
                                    unsigned divisor_min_bits, BN_CTX *ctx);
625
626
// bn_is_relatively_prime checks whether GCD(`x`, `y`) is one. On success, it
627
// returns one and sets `*out_relatively_prime` to one if the GCD was one and
628
// zero otherwise. On error, it returns zero.
629
OPENSSL_EXPORT int bn_is_relatively_prime(int *out_relatively_prime,
630
                                          const BIGNUM *x, const BIGNUM *y,
631
                                          BN_CTX *ctx);
632
633
// bn_lcm_consttime sets `r` to LCM(`a`, `b`). It returns one and success and
634
// zero on error. `a` and `b` are both treated as secret.
635
OPENSSL_EXPORT int bn_lcm_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
636
                                    BN_CTX *ctx);
637
638
// bn_mont_ctx_init zero-initialies `mont`.
639
void bn_mont_ctx_init(BN_MONT_CTX *mont);
640
641
// bn_mont_ctx_cleanup releases memory associated with `mont`, without freeing
642
// `mont` itself.
643
void bn_mont_ctx_cleanup(BN_MONT_CTX *mont);
644
645
646
// Constant-time modular arithmetic.
647
//
648
// The following functions implement basic constant-time modular arithmetic.
649
650
// bn_mod_add_words sets `r` to `a` + `b` (mod `m`), using `tmp` as scratch
651
// space. Each array is `num` words long. `a` and `b` must be < `m`. Any pair of
652
// `r`, `a`, and `b` may alias.
653
void bn_mod_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
654
                      const BN_ULONG *m, BN_ULONG *tmp, size_t num);
655
656
// bn_mod_add_consttime acts like `BN_mod_add_quick` but takes a `BN_CTX`.
657
int bn_mod_add_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
658
                         const BIGNUM *m, BN_CTX *ctx);
659
660
// bn_mod_sub_words sets `r` to `a` - `b` (mod `m`), using `tmp` as scratch
661
// space. Each array is `num` words long. `a` and `b` must be < `m`. Any pair of
662
// `r`, `a`, and `b` may alias.
663
void bn_mod_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
664
                      const BN_ULONG *m, BN_ULONG *tmp, size_t num);
665
666
// bn_mod_sub_consttime acts like `BN_mod_sub_quick` but takes a `BN_CTX`.
667
int bn_mod_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
668
                         const BIGNUM *m, BN_CTX *ctx);
669
670
// bn_mod_lshift1_consttime acts like `BN_mod_lshift1_quick` but takes a
671
// `BN_CTX`.
672
int bn_mod_lshift1_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *m,
673
                             BN_CTX *ctx);
674
675
// bn_mod_lshift_consttime acts like `BN_mod_lshift_quick` but takes a `BN_CTX`.
676
int bn_mod_lshift_consttime(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
677
                            BN_CTX *ctx);
678
679
// bn_mod_inverse_consttime sets `r` to `a`^-1, mod `n`. `a` must be non-
680
// negative and less than `n`. It returns one on success and zero on error. On
681
// failure, if the failure was caused by `a` having no inverse mod `n` then
682
// `*out_no_inverse` will be set to one; otherwise it will be set to zero.
683
//
684
// This function treats both `a` and `n` as secret, provided they are both non-
685
// zero and the inverse exists. It should only be used for even moduli where
686
// none of the less general implementations are applicable.
687
OPENSSL_EXPORT int bn_mod_inverse_consttime(BIGNUM *r, int *out_no_inverse,
688
                                            const BIGNUM *a, const BIGNUM *n,
689
                                            BN_CTX *ctx);
690
691
// bn_mod_inverse_prime sets `out` to the modular inverse of `a` modulo `p`,
692
// computed with Fermat's Little Theorem. It returns one on success and zero on
693
// error. If `mont_p` is NULL, one will be computed temporarily.
694
int bn_mod_inverse_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p,
695
                         BN_CTX *ctx, const BN_MONT_CTX *mont_p);
696
697
// bn_mod_inverse_secret_prime behaves like `bn_mod_inverse_prime` but uses
698
// `BN_mod_exp_mont_consttime` instead of `BN_mod_exp_mont` in hopes of
699
// protecting the exponent.
700
int bn_mod_inverse_secret_prime(BIGNUM *out, const BIGNUM *a, const BIGNUM *p,
701
                                BN_CTX *ctx, const BN_MONT_CTX *mont_p);
702
703
// BN_MONT_CTX_set_locked takes `lock` and checks whether `*pmont` is NULL. If
704
// so, it creates a new `BN_MONT_CTX` and sets the modulus for it to `mod`. It
705
// then stores it as `*pmont`. It returns one on success and zero on error. Note
706
// this function assumes `mod` is public.
707
//
708
// If `*pmont` is already non-NULL then it does nothing and returns one.
709
int BN_MONT_CTX_set_locked(UniquePtr<BN_MONT_CTX> *pmont, Mutex *lock,
710
                           const BIGNUM *mod, BN_CTX *bn_ctx);
711
712
713
// Low-level operations for small numbers.
714
//
715
// The following functions implement algorithms suitable for use with scalars
716
// and field elements in elliptic curves. They rely on the number being small
717
// both to stack-allocate various temporaries and because they do not implement
718
// optimizations useful for the larger values used in RSA.
719
720
// BN_SMALL_MAX_WORDS is the largest size input these functions handle. This
721
// limit allows temporaries to be more easily stack-allocated. This limit is set
722
// to accommodate P-521.
723
#if defined(OPENSSL_32_BIT)
724
#define BN_SMALL_MAX_WORDS 17
725
#else
726
123M
#define BN_SMALL_MAX_WORDS 9
727
#endif
728
729
// bn_mul_small sets `r` to `a`*`b`. `num_r` must be `num_a` + `num_b`. `r` may
730
// not alias with `a` or `b`.
731
void bn_mul_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a,
732
                 const BN_ULONG *b, size_t num_b);
733
734
// bn_sqr_small sets `r` to `a`². `num_r` must be `num_a`*2. `r` and `a` may
735
// not alias.
736
void bn_sqr_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a);
737
738
// In the following functions, the modulus must be at most `BN_SMALL_MAX_WORDS`
739
// words long.
740
741
// bn_to_montgomery_small sets `r` to `a` translated to the Montgomery domain.
742
// `r` and `a` are `num` words long, which must be `mont->N.width`. `a` must be
743
// fully reduced and may alias `r`.
744
void bn_to_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
745
                            const BN_MONT_CTX *mont);
746
747
// bn_from_montgomery_small sets `r` to `a` translated out of the Montgomery
748
// domain. `r` and `a` are `num_r` and `num_a` words long, respectively. `num_r`
749
// must be `mont->N.width`. `a` must be at most `mont->N`² and may alias `r`.
750
//
751
// Unlike most of these functions, only `num_r` is bounded by
752
// `BN_SMALL_MAX_WORDS`. `num_a` may exceed it, but must be at most 2 * `num_r`.
753
void bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
754
                              size_t num_a, const BN_MONT_CTX *mont);
755
756
// bn_mod_mul_montgomery_small sets `r` to `a` * `b` mod `mont->N`. Both inputs
757
// and outputs are in the Montgomery domain. Each array is `num` words long,
758
// which must be `mont->N.width`. Any two of `r`, `a`, and `b` may alias. `a`
759
// and `b` must be reduced on input.
760
void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a,
761
                                 const BN_ULONG *b, size_t num,
762
                                 const BN_MONT_CTX *mont);
763
764
// bn_mod_exp_mont_small sets `r` to `a`^`p` mod `mont->N`. It returns one on
765
// success and zero on programmer or internal error. Both inputs and outputs are
766
// in the Montgomery domain. `r` and `a` are `num` words long, which must be
767
// `mont->N.width` and at most `BN_SMALL_MAX_WORDS`. `num_p`, measured in bits,
768
// must fit in `size_t`. `a` must be fully-reduced. This function runs in time
769
// independent of `a`, but `p` and `mont->N` are public values. `a` must be
770
// fully-reduced and may alias with `r`.
771
//
772
// Note this function differs from `BN_mod_exp_mont` which uses Montgomery
773
// reduction but takes input and output outside the Montgomery domain. Combine
774
// this function with `bn_from_montgomery_small` and `bn_to_montgomery_small`
775
// if necessary.
776
void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
777
                           const BN_ULONG *p, size_t num_p,
778
                           const BN_MONT_CTX *mont);
779
780
// bn_mod_inverse0_prime_mont_small sets `r` to `a`^-1 mod `mont->N`. If `a` is
781
// zero, `r` is set to zero. `mont->N` must be a prime. `r` and `a` are `num`
782
// words long, which must be `mont->N.width` and at most `BN_SMALL_MAX_WORDS`.
783
// `a` must be fully-reduced and may alias `r`. This function runs in time
784
// independent of `a`, but `mont->N` is a public value.
785
void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a,
786
                                      size_t num, const BN_MONT_CTX *mont);
787
788
789
// Word-based byte conversion functions.
790
791
// bn_big_endian_to_words interprets `in_len` bytes from `in` as a big-endian,
792
// unsigned integer and writes the result to `out_len` words in `out`. `out_len`
793
// must be large enough to represent any `in_len`-byte value. That is, `in_len`
794
// must be at most `BN_BYTES * out_len`.
795
void bn_big_endian_to_words(BN_ULONG *out, size_t out_len, const uint8_t *in,
796
                            size_t in_len);
797
798
// bn_words_to_big_endian represents `in_len` words from `in` as a big-endian,
799
// unsigned integer in `out_len` bytes. It writes the result to `out`. `out_len`
800
// must be large enough to represent `in` without truncation.
801
//
802
// Note `out_len` may be less than `BN_BYTES * in_len` if `in` is known to have
803
// leading zeros.
804
void bn_words_to_big_endian(uint8_t *out, size_t out_len, const BN_ULONG *in,
805
                            size_t in_len);
806
807
BSSL_NAMESPACE_END
808
809
810
#endif  // OPENSSL_HEADER_CRYPTO_FIPSMODULE_BN_INTERNAL_H