New "i15" implementation of big integers (faster, and constant-time, on ARM Cortex...
[BearSSL] / src / inner.h
1 /*
2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25 #ifndef INNER_H__
26 #define INNER_H__
27
28 #include <string.h>
29 #include <limits.h>
30
31 #include "config.h"
32 #include "bearssl.h"
33
34 /*
35 * Maximum size for a RSA modulus (in bits). Allocated stack buffers
36 * depend on that size, so this value should be kept small. Currently,
37 * 2048-bit RSA keys offer adequate security, and should still do so for
38 * the next few decades; however, a number of widespread PKI have
39 * already set their root keys to RSA-4096, so we should be able to
40 * process such keys.
41 *
42 * This value MUST be a multiple of 64.
43 */
44 #define BR_MAX_RSA_SIZE 4096
45
46 /*
47 * Maximum size for a RSA factor (in bits). This is for RSA private-key
48 * operations. Default is to support factors up to a bit more than half
49 * the maximum modulus size.
50 *
51 * This value MUST be a multiple of 32.
52 */
53 #define BR_MAX_RSA_FACTOR ((BR_MAX_RSA_SIZE + 64) >> 1)
54
55 /*
56 * Maximum size for an EC curve (modulus or order), in bits. Size of
57 * stack buffers depends on that parameter. This size MUST be a multiple
58 * of 8 (so that decoding an integer with that many bytes does not
59 * overflow).
60 */
61 #define BR_MAX_EC_SIZE 528
62
63 /*
64 * Some macros to recognize the current architecture. Right now, we are
65 * interested into automatically recognizing architecture with efficient
66 * 64-bit types so that we may automatically use implementations that
67 * use 64-bit registers in that case. Future versions may detect, e.g.,
68 * availability of SSE2 intrinsics.
69 *
70 * If 'unsigned long' is a 64-bit type, then we assume that 64-bit types
71 * are efficient. Otherwise, we rely on macros that depend on compiler,
72 * OS and architecture. In any case, failure to detect the architecture
73 * as 64-bit means that the 32-bit code will be used, and that code
74 * works also on 64-bit architectures (the 64-bit code may simply be
75 * more efficient).
76 *
77 * The test on 'unsigned long' should already catch most cases, the one
78 * notable exception being Windows code where 'unsigned long' is kept to
79 * 32-bit for compatbility with all the legacy code that liberally uses
80 * the 'DWORD' type for 32-bit values.
81 *
82 * Macro names are taken from: http://nadeausoftware.com/articles/2012/02/c_c_tip_how_detect_processor_type_using_compiler_predefined_macros
83 */
84 #ifndef BR_64
85 #if ((ULONG_MAX >> 31) >> 31) == 3
86 #define BR_64 1
87 #elif defined(__ia64) || defined(__itanium__) || defined(_M_IA64)
88 #define BR_64 1
89 #elif defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) \
90 || defined(__64BIT__) || defined(_LP64) || defined(__LP64__)
91 #define BR_64 1
92 #elif defined(__sparc64__)
93 #define BR_64 1
94 #elif defined(__x86_64__) || defined(_M_X64)
95 #define BR_64 1
96 #endif
97 #endif
98
99 /* ==================================================================== */
100 /*
101 * Encoding/decoding functions.
102 *
103 * 32-bit and 64-bit decoding, both little-endian and big-endian, is
104 * implemented with the inline functions below. These functions are
105 * generic: they don't depend on the architecture natural endianness,
106 * and they can handle unaligned accesses. Optimized versions for some
107 * specific architectures may be implemented at a later time.
108 */
109
110 static inline void
111 br_enc16le(void *dst, unsigned x)
112 {
113 unsigned char *buf;
114
115 buf = dst;
116 buf[0] = (unsigned char)x;
117 buf[1] = (unsigned char)(x >> 8);
118 }
119
120 static inline void
121 br_enc16be(void *dst, unsigned x)
122 {
123 unsigned char *buf;
124
125 buf = dst;
126 buf[0] = (unsigned char)(x >> 8);
127 buf[1] = (unsigned char)x;
128 }
129
130 static inline unsigned
131 br_dec16le(const void *src)
132 {
133 const unsigned char *buf;
134
135 buf = src;
136 return (unsigned)buf[0] | ((unsigned)buf[1] << 8);
137 }
138
139 static inline unsigned
140 br_dec16be(const void *src)
141 {
142 const unsigned char *buf;
143
144 buf = src;
145 return ((unsigned)buf[0] << 8) | (unsigned)buf[1];
146 }
147
148 static inline void
149 br_enc32le(void *dst, uint32_t x)
150 {
151 unsigned char *buf;
152
153 buf = dst;
154 buf[0] = (unsigned char)x;
155 buf[1] = (unsigned char)(x >> 8);
156 buf[2] = (unsigned char)(x >> 16);
157 buf[3] = (unsigned char)(x >> 24);
158 }
159
160 static inline void
161 br_enc32be(void *dst, uint32_t x)
162 {
163 unsigned char *buf;
164
165 buf = dst;
166 buf[0] = (unsigned char)(x >> 24);
167 buf[1] = (unsigned char)(x >> 16);
168 buf[2] = (unsigned char)(x >> 8);
169 buf[3] = (unsigned char)x;
170 }
171
172 static inline uint32_t
173 br_dec32le(const void *src)
174 {
175 const unsigned char *buf;
176
177 buf = src;
178 return (uint32_t)buf[0]
179 | ((uint32_t)buf[1] << 8)
180 | ((uint32_t)buf[2] << 16)
181 | ((uint32_t)buf[3] << 24);
182 }
183
184 static inline uint32_t
185 br_dec32be(const void *src)
186 {
187 const unsigned char *buf;
188
189 buf = src;
190 return ((uint32_t)buf[0] << 24)
191 | ((uint32_t)buf[1] << 16)
192 | ((uint32_t)buf[2] << 8)
193 | (uint32_t)buf[3];
194 }
195
196 static inline void
197 br_enc64le(void *dst, uint64_t x)
198 {
199 unsigned char *buf;
200
201 buf = dst;
202 br_enc32le(buf, (uint32_t)x);
203 br_enc32le(buf + 4, (uint32_t)(x >> 32));
204 }
205
206 static inline void
207 br_enc64be(void *dst, uint64_t x)
208 {
209 unsigned char *buf;
210
211 buf = dst;
212 br_enc32be(buf, (uint32_t)(x >> 32));
213 br_enc32be(buf + 4, (uint32_t)x);
214 }
215
216 static inline uint64_t
217 br_dec64le(const void *src)
218 {
219 const unsigned char *buf;
220
221 buf = src;
222 return (uint64_t)br_dec32le(buf)
223 | ((uint64_t)br_dec32le(buf + 4) << 32);
224 }
225
226 static inline uint64_t
227 br_dec64be(const void *src)
228 {
229 const unsigned char *buf;
230
231 buf = src;
232 return ((uint64_t)br_dec32be(buf) << 32)
233 | (uint64_t)br_dec32be(buf + 4);
234 }
235
236 /*
237 * Range decoding and encoding (for several successive values).
238 */
239 void br_range_dec16le(uint16_t *v, size_t num, const void *src);
240 void br_range_dec16be(uint16_t *v, size_t num, const void *src);
241 void br_range_enc16le(void *dst, const uint16_t *v, size_t num);
242 void br_range_enc16be(void *dst, const uint16_t *v, size_t num);
243
244 void br_range_dec32le(uint32_t *v, size_t num, const void *src);
245 void br_range_dec32be(uint32_t *v, size_t num, const void *src);
246 void br_range_enc32le(void *dst, const uint32_t *v, size_t num);
247 void br_range_enc32be(void *dst, const uint32_t *v, size_t num);
248
249 void br_range_dec64le(uint64_t *v, size_t num, const void *src);
250 void br_range_dec64be(uint64_t *v, size_t num, const void *src);
251 void br_range_enc64le(void *dst, const uint64_t *v, size_t num);
252 void br_range_enc64be(void *dst, const uint64_t *v, size_t num);
253
254 /*
255 * Byte-swap a 32-bit integer.
256 */
257 static inline uint32_t
258 br_swap32(uint32_t x)
259 {
260 x = ((x & (uint32_t)0x00FF00FF) << 8)
261 | ((x >> 8) & (uint32_t)0x00FF00FF);
262 return (x << 16) | (x >> 16);
263 }
264
265 /* ==================================================================== */
266 /*
267 * Support code for hash functions.
268 */
269
270 /*
271 * IV for MD5, SHA-1, SHA-224 and SHA-256.
272 */
273 extern const uint32_t br_md5_IV[];
274 extern const uint32_t br_sha1_IV[];
275 extern const uint32_t br_sha224_IV[];
276 extern const uint32_t br_sha256_IV[];
277
278 /*
279 * Round functions for MD5, SHA-1, SHA-224 and SHA-256 (SHA-224 and
280 * SHA-256 use the same round function).
281 */
282 void br_md5_round(const unsigned char *buf, uint32_t *val);
283 void br_sha1_round(const unsigned char *buf, uint32_t *val);
284 void br_sha2small_round(const unsigned char *buf, uint32_t *val);
285
286 /*
287 * The core function for the TLS PRF. It computes
288 * P_hash(secret, label + seed), and XORs the result into the dst buffer.
289 */
290 void br_tls_phash(void *dst, size_t len,
291 const br_hash_class *dig,
292 const void *secret, size_t secret_len,
293 const char *label, const void *seed, size_t seed_len);
294
295 /*
296 * Copy all configured hash implementations from a multihash context
297 * to another.
298 */
299 static inline void
300 br_multihash_copyimpl(br_multihash_context *dst,
301 const br_multihash_context *src)
302 {
303 memcpy(dst->impl, src->impl, sizeof src->impl);
304 }
305
306 /* ==================================================================== */
307 /*
308 * Constant-time primitives. These functions manipulate 32-bit values in
309 * order to provide constant-time comparisons and multiplexers.
310 *
311 * Boolean values (the "ctl" bits) MUST have value 0 or 1.
312 *
313 * Implementation notes:
314 * =====================
315 *
316 * The uintN_t types are unsigned and with width exactly N bits; the C
317 * standard guarantees that computations are performed modulo 2^N, and
318 * there can be no overflow. Negation (unary '-') works on unsigned types
319 * as well.
320 *
321 * The intN_t types are guaranteed to have width exactly N bits, with no
322 * padding bit, and using two's complement representation. Casting
323 * intN_t to uintN_t really is conversion modulo 2^N. Beware that intN_t
324 * types, being signed, trigger implementation-defined behaviour on
325 * overflow (including raising some signal): with GCC, while modular
326 * arithmetics are usually applied, the optimizer may assume that
327 * overflows don't occur (unless the -fwrapv command-line option is
328 * added); Clang has the additional -ftrapv option to explicitly trap on
329 * integer overflow or underflow.
330 */
331
332 /*
333 * Negate a boolean.
334 */
335 static inline uint32_t
336 NOT(uint32_t ctl)
337 {
338 return ctl ^ 1;
339 }
340
341 /*
342 * Multiplexer: returns x if ctl == 1, y if ctl == 0.
343 */
344 static inline uint32_t
345 MUX(uint32_t ctl, uint32_t x, uint32_t y)
346 {
347 return y ^ (-ctl & (x ^ y));
348 }
349
350 /*
351 * Equality check: returns 1 if x == y, 0 otherwise.
352 */
353 static inline uint32_t
354 EQ(uint32_t x, uint32_t y)
355 {
356 uint32_t q;
357
358 q = x ^ y;
359 return NOT((q | -q) >> 31);
360 }
361
362 /*
363 * Inequality check: returns 1 if x != y, 0 otherwise.
364 */
365 static inline uint32_t
366 NEQ(uint32_t x, uint32_t y)
367 {
368 uint32_t q;
369
370 q = x ^ y;
371 return (q | -q) >> 31;
372 }
373
374 /*
375 * Comparison: returns 1 if x > y, 0 otherwise.
376 */
377 static inline uint32_t
378 GT(uint32_t x, uint32_t y)
379 {
380 /*
381 * If both x < 2^31 and x < 2^31, then y-x will have its high
382 * bit set if x > y, cleared otherwise.
383 *
384 * If either x >= 2^31 or y >= 2^31 (but not both), then the
385 * result is the high bit of x.
386 *
387 * If both x >= 2^31 and y >= 2^31, then we can virtually
388 * subtract 2^31 from both, and we are back to the first case.
389 * Since (y-2^31)-(x-2^31) = y-x, the subtraction is already
390 * fine.
391 */
392 uint32_t z;
393
394 z = y - x;
395 return (z ^ ((x ^ y) & (x ^ z))) >> 31;
396 }
397
398 /*
399 * Other comparisons (greater-or-equal, lower-than, lower-or-equal).
400 */
401 #define GE(x, y) NOT(GT(y, x))
402 #define LT(x, y) GT(y, x)
403 #define LE(x, y) NOT(GT(x, y))
404
405 /*
406 * General comparison: returned value is -1, 0 or 1, depending on
407 * whether x is lower than, equal to, or greater than y.
408 */
409 static inline int32_t
410 CMP(uint32_t x, uint32_t y)
411 {
412 return (int32_t)GT(x, y) | -(int32_t)GT(y, x);
413 }
414
415 /*
416 * Returns 1 if x == 0, 0 otherwise. Take care that the operand is signed.
417 */
418 static inline uint32_t
419 EQ0(int32_t x)
420 {
421 uint32_t q;
422
423 q = (uint32_t)x;
424 return ~(q | -q) >> 31;
425 }
426
427 /*
428 * Returns 1 if x > 0, 0 otherwise. Take care that the operand is signed.
429 */
430 static inline uint32_t
431 GT0(int32_t x)
432 {
433 /*
434 * High bit of -x is 0 if x == 0, but 1 if x > 0.
435 */
436 uint32_t q;
437
438 q = (uint32_t)x;
439 return (~q & -q) >> 31;
440 }
441
442 /*
443 * Returns 1 if x >= 0, 0 otherwise. Take care that the operand is signed.
444 */
445 static inline uint32_t
446 GE0(int32_t x)
447 {
448 return ~(uint32_t)x >> 31;
449 }
450
451 /*
452 * Returns 1 if x < 0, 0 otherwise. Take care that the operand is signed.
453 */
454 static inline uint32_t
455 LT0(int32_t x)
456 {
457 return (uint32_t)x >> 31;
458 }
459
460 /*
461 * Returns 1 if x <= 0, 0 otherwise. Take care that the operand is signed.
462 */
463 static inline uint32_t
464 LE0(int32_t x)
465 {
466 uint32_t q;
467
468 /*
469 * ~-x has its high bit set if and only if -x is nonnegative (as
470 * a signed int), i.e. x is in the -(2^31-1) to 0 range. We must
471 * do an OR with x itself to account for x = -2^31.
472 */
473 q = (uint32_t)x;
474 return (q | ~-q) >> 31;
475 }
476
477 /*
478 * Conditional copy: src[] is copied into dst[] if and only if ctl is 1.
479 * dst[] and src[] may overlap completely (but not partially).
480 */
481 void br_ccopy(uint32_t ctl, void *dst, const void *src, size_t len);
482
483 #define CCOPY br_ccopy
484
485 /*
486 * Compute the bit length of a 32-bit integer. Returned value is between 0
487 * and 32 (inclusive).
488 */
489 static inline uint32_t
490 BIT_LENGTH(uint32_t x)
491 {
492 uint32_t k, c;
493
494 k = NEQ(x, 0);
495 c = GT(x, 0xFFFF); x = MUX(c, x >> 16, x); k += c << 4;
496 c = GT(x, 0x00FF); x = MUX(c, x >> 8, x); k += c << 3;
497 c = GT(x, 0x000F); x = MUX(c, x >> 4, x); k += c << 2;
498 c = GT(x, 0x0003); x = MUX(c, x >> 2, x); k += c << 1;
499 k += GT(x, 0x0001);
500 return k;
501 }
502
503 /*
504 * Compute the minimum of x and y.
505 */
506 static inline uint32_t
507 MIN(uint32_t x, uint32_t y)
508 {
509 return MUX(GT(x, y), y, x);
510 }
511
512 /*
513 * Compute the maximum of x and y.
514 */
515 static inline uint32_t
516 MAX(uint32_t x, uint32_t y)
517 {
518 return MUX(GT(x, y), x, y);
519 }
520
521 /*
522 * Multiply two 32-bit integers, with a 64-bit result. This default
523 * implementation assumes that the basic multiplication operator
524 * yields constant-time code.
525 */
526 #define MUL(x, y) ((uint64_t)(x) * (uint64_t)(y))
527
528 #if BR_CT_MUL31
529
530 /*
531 * Alternate implementation of MUL31, that will be constant-time on some
532 * (old) platforms where the default MUL31 is not. Unfortunately, it is
533 * also substantially slower, and yields larger code, on more modern
534 * platforms, which is why it is deactivated by default.
535 *
536 * MUL31_lo() must do some extra work because on some platforms, the
537 * _signed_ multiplication may return early if the top bits are 1.
538 * Simply truncating (casting) the output of MUL31() would not be
539 * sufficient, because the compiler may notice that we keep only the low
540 * word, and then replace automatically the unsigned multiplication with
541 * a signed multiplication opcode.
542 */
543 #define MUL31(x, y) ((uint64_t)((x) | (uint32_t)0x80000000) \
544 * (uint64_t)((y) | (uint32_t)0x80000000) \
545 - ((uint64_t)(x) << 31) - ((uint64_t)(y) << 31) \
546 - ((uint64_t)1 << 62))
547 static inline uint32_t
548 MUL31_lo(uint32_t x, uint32_t y)
549 {
550 uint32_t xl, xh;
551 uint32_t yl, yh;
552
553 xl = (x & 0xFFFF) | (uint32_t)0x80000000;
554 xh = (x >> 16) | (uint32_t)0x80000000;
555 yl = (y & 0xFFFF) | (uint32_t)0x80000000;
556 yh = (y >> 16) | (uint32_t)0x80000000;
557 return (xl * yl + ((xl * yh + xh * yl) << 16)) & (uint32_t)0x7FFFFFFF;
558 }
559
560 #else
561
562 /*
563 * Multiply two 31-bit integers, with a 62-bit result. This default
564 * implementation assumes that the basic multiplication operator
565 * yields constant-time code.
566 * The MUL31_lo() macro returns only the low 31 bits of the product.
567 */
568 #define MUL31(x, y) ((uint64_t)(x) * (uint64_t)(y))
569 #define MUL31_lo(x, y) (((uint32_t)(x) * (uint32_t)(y)) & (uint32_t)0x7FFFFFFF)
570
571 #endif
572
573 /*
574 * Multiply two words together; each word may contain up to 15 bits of
575 * data. If BR_CT_MUL15 is non-zero, then the macro will contain some
576 * extra operations that help in making the operation constant-time on
577 * some platforms, where the basic 32-bit multiplication is not
578 * constant-time.
579 */
580 #if BR_CT_MUL15
581 #define MUL15(x, y) (((uint32_t)(x) | (uint32_t)0x80000000) \
582 * ((uint32_t)(y) | (uint32_t)0x80000000) \
583 & (uint32_t)0x3FFFFFFF)
584 #else
585 #define MUL15(x, y) ((uint32_t)(x) * (uint32_t)(y))
586 #endif
587
588 /*
589 * Arithmetic right shift (sign bit is copied). What happens when
590 * right-shifting a negative value is _implementation-defined_, so it
591 * does not trigger undefined behaviour, but it is still up to each
592 * compiler to define (and document) what it does. Most/all compilers
593 * will do an arithmetic shift, the sign bit being used to fill the
594 * holes; this is a native operation on the underlying CPU, and it would
595 * make little sense for the compiler to do otherwise. GCC explicitly
596 * documents that it follows that convention.
597 *
598 * Still, if BR_NO_ARITH_SHIFT is defined (and non-zero), then an
599 * alternate version will be used, that does not rely on such
600 * implementation-defined behaviour. Unfortunately, it is also slower
601 * and yields bigger code, which is why it is deactivated by default.
602 */
603 #if BR_NO_ARITH_SHIFT
604 #define ARSH(x, n) (((uint32_t)(x) >> (n)) \
605 | ((-((uint32_t)(x) >> 31)) << (32 - (n))))
606 #else
607 #define ARSH(x, n) ((*(int32_t *)&(x)) >> (n))
608 #endif
609
610 /*
611 * Constant-time division. The dividend hi:lo is divided by the
612 * divisor d; the quotient is returned and the remainder is written
613 * in *r. If hi == d, then the quotient does not fit on 32 bits;
614 * returned value is thus truncated. If hi > d, returned values are
615 * indeterminate.
616 */
617 uint32_t br_divrem(uint32_t hi, uint32_t lo, uint32_t d, uint32_t *r);
618
619 /*
620 * Wrapper for br_divrem(); the remainder is returned, and the quotient
621 * is discarded.
622 */
623 static inline uint32_t
624 br_rem(uint32_t hi, uint32_t lo, uint32_t d)
625 {
626 uint32_t r;
627
628 br_divrem(hi, lo, d, &r);
629 return r;
630 }
631
632 /*
633 * Wrapper for br_divrem(); the quotient is returned, and the remainder
634 * is discarded.
635 */
636 static inline uint32_t
637 br_div(uint32_t hi, uint32_t lo, uint32_t d)
638 {
639 uint32_t r;
640
641 return br_divrem(hi, lo, d, &r);
642 }
643
644 /* ==================================================================== */
645
646 /*
647 * Integers 'i32'
648 * --------------
649 *
650 * The 'i32' functions implement computations on big integers using
651 * an internal representation as an array of 32-bit integers. For
652 * an array x[]:
653 * -- x[0] contains the "announced bit length" of the integer
654 * -- x[1], x[2]... contain the value in little-endian order (x[1]
655 * contains the least significant 32 bits)
656 *
657 * Multiplications rely on the elementary 32x32->64 multiplication.
658 *
659 * The announced bit length specifies the number of bits that are
660 * significant in the subsequent 32-bit words. Unused bits in the
661 * last (most significant) word are set to 0; subsequent words are
662 * uninitialized and need not exist at all.
663 *
664 * The execution time and memory access patterns of all computations
665 * depend on the announced bit length, but not on the actual word
666 * values. For modular integers, the announced bit length of any integer
667 * modulo n is equal to the actual bit length of n; thus, computations
668 * on modular integers are "constant-time" (only the modulus length may
669 * leak).
670 */
671
672 /*
673 * Compute the actual bit length of an integer. The argument x should
674 * point to the first (least significant) value word of the integer.
675 * The len 'xlen' contains the number of 32-bit words to access.
676 *
677 * CT: value or length of x does not leak.
678 */
679 uint32_t br_i32_bit_length(uint32_t *x, size_t xlen);
680
681 /*
682 * Decode an integer from its big-endian unsigned representation. The
683 * "true" bit length of the integer is computed, but all words of x[]
684 * corresponding to the full 'len' bytes of the source are set.
685 *
686 * CT: value or length of x does not leak.
687 */
688 void br_i32_decode(uint32_t *x, const void *src, size_t len);
689
690 /*
691 * Decode an integer from its big-endian unsigned representation. The
692 * integer MUST be lower than m[]; the announced bit length written in
693 * x[] will be equal to that of m[]. All 'len' bytes from the source are
694 * read.
695 *
696 * Returned value is 1 if the decode value fits within the modulus, 0
697 * otherwise. In the latter case, the x[] buffer will be set to 0 (but
698 * still with the announced bit length of m[]).
699 *
700 * CT: value or length of x does not leak. Memory access pattern depends
701 * only of 'len' and the announced bit length of m. Whether x fits or
702 * not does not leak either.
703 */
704 uint32_t br_i32_decode_mod(uint32_t *x,
705 const void *src, size_t len, const uint32_t *m);
706
707 /*
708 * Reduce an integer (a[]) modulo another (m[]). The result is written
709 * in x[] and its announced bit length is set to be equal to that of m[].
710 *
711 * x[] MUST be distinct from a[] and m[].
712 *
713 * CT: only announced bit lengths leak, not values of x, a or m.
714 */
715 void br_i32_reduce(uint32_t *x, const uint32_t *a, const uint32_t *m);
716
717 /*
718 * Decode an integer from its big-endian unsigned representation, and
719 * reduce it modulo the provided modulus m[]. The announced bit length
720 * of the result is set to be equal to that of the modulus.
721 *
722 * x[] MUST be distinct from m[].
723 */
724 void br_i32_decode_reduce(uint32_t *x,
725 const void *src, size_t len, const uint32_t *m);
726
727 /*
728 * Encode an integer into its big-endian unsigned representation. The
729 * output length in bytes is provided (parameter 'len'); if the length
730 * is too short then the integer is appropriately truncated; if it is
731 * too long then the extra bytes are set to 0.
732 */
733 void br_i32_encode(void *dst, size_t len, const uint32_t *x);
734
735 /*
736 * Multiply x[] by 2^32 and then add integer z, modulo m[]. This
737 * function assumes that x[] and m[] have the same announced bit
738 * length, and the announced bit length of m[] matches its true
739 * bit length.
740 *
741 * x[] and m[] MUST be distinct arrays.
742 *
743 * CT: only the common announced bit length of x and m leaks, not
744 * the values of x, z or m.
745 */
746 void br_i32_muladd_small(uint32_t *x, uint32_t z, const uint32_t *m);
747
748 /*
749 * Extract one word from an integer. The offset is counted in bits.
750 * The word MUST entirely fit within the word elements corresponding
751 * to the announced bit length of a[].
752 */
753 static inline uint32_t
754 br_i32_word(const uint32_t *a, uint32_t off)
755 {
756 size_t u;
757 unsigned j;
758
759 u = (size_t)(off >> 5) + 1;
760 j = (unsigned)off & 31;
761 if (j == 0) {
762 return a[u];
763 } else {
764 return (a[u] >> j) | (a[u + 1] << (32 - j));
765 }
766 }
767
768 /*
769 * Test whether an integer is zero.
770 */
771 uint32_t br_i32_iszero(const uint32_t *x);
772
773 /*
774 * Add b[] to a[] and return the carry (0 or 1). If ctl is 0, then a[]
775 * is unmodified, but the carry is still computed and returned. The
776 * arrays a[] and b[] MUST have the same announced bit length.
777 *
778 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
779 */
780 uint32_t br_i32_add(uint32_t *a, const uint32_t *b, uint32_t ctl);
781
782 /*
783 * Subtract b[] from a[] and return the carry (0 or 1). If ctl is 0,
784 * then a[] is unmodified, but the carry is still computed and returned.
785 * The arrays a[] and b[] MUST have the same announced bit length.
786 *
787 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
788 */
789 uint32_t br_i32_sub(uint32_t *a, const uint32_t *b, uint32_t ctl);
790
791 /*
792 * Compute d+a*b, result in d. The initial announced bit length of d[]
793 * MUST match that of a[]. The d[] array MUST be large enough to
794 * accommodate the full result, plus (possibly) an extra word. The
795 * resulting announced bit length of d[] will be the sum of the announced
796 * bit lengths of a[] and b[] (therefore, it may be larger than the actual
797 * bit length of the numerical result).
798 *
799 * a[] and b[] may be the same array. d[] must be disjoint from both a[]
800 * and b[].
801 */
802 void br_i32_mulacc(uint32_t *d, const uint32_t *a, const uint32_t *b);
803
804 /*
805 * Zeroize an integer. The announced bit length is set to the provided
806 * value, and the corresponding words are set to 0.
807 */
808 static inline void
809 br_i32_zero(uint32_t *x, uint32_t bit_len)
810 {
811 *x ++ = bit_len;
812 memset(x, 0, ((bit_len + 31) >> 5) * sizeof *x);
813 }
814
815 /*
816 * Compute -(1/x) mod 2^32. If x is even, then this function returns 0.
817 */
818 uint32_t br_i32_ninv32(uint32_t x);
819
820 /*
821 * Convert a modular integer to Montgomery representation. The integer x[]
822 * MUST be lower than m[], but with the same announced bit length.
823 */
824 void br_i32_to_monty(uint32_t *x, const uint32_t *m);
825
826 /*
827 * Convert a modular integer back from Montgomery representation. The
828 * integer x[] MUST be lower than m[], but with the same announced bit
829 * length. The "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is
830 * the least significant value word of m[] (this works only if m[] is
831 * an odd integer).
832 */
833 void br_i32_from_monty(uint32_t *x, const uint32_t *m, uint32_t m0i);
834
835 /*
836 * Compute a modular Montgomery multiplication. d[] is filled with the
837 * value of x*y/R modulo m[] (where R is the Montgomery factor). The
838 * array d[] MUST be distinct from x[], y[] and m[]. x[] and y[] MUST be
839 * numerically lower than m[]. x[] and y[] MAY be the same array. The
840 * "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is the least
841 * significant value word of m[] (this works only if m[] is an odd
842 * integer).
843 */
844 void br_i32_montymul(uint32_t *d, const uint32_t *x, const uint32_t *y,
845 const uint32_t *m, uint32_t m0i);
846
847 /*
848 * Compute a modular exponentiation. x[] MUST be an integer modulo m[]
849 * (same announced bit length, lower value). m[] MUST be odd. The
850 * exponent is in big-endian unsigned notation, over 'elen' bytes. The
851 * "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is the least
852 * significant value word of m[] (this works only if m[] is an odd
853 * integer). The t1[] and t2[] parameters must be temporary arrays,
854 * each large enough to accommodate an integer with the same size as m[].
855 */
856 void br_i32_modpow(uint32_t *x, const unsigned char *e, size_t elen,
857 const uint32_t *m, uint32_t m0i, uint32_t *t1, uint32_t *t2);
858
859 /* ==================================================================== */
860
861 /*
862 * Integers 'i31'
863 * --------------
864 *
865 * The 'i31' functions implement computations on big integers using
866 * an internal representation as an array of 32-bit integers. For
867 * an array x[]:
868 * -- x[0] encodes the array length and the "announced bit length"
869 * of the integer: namely, if the announced bit length is k,
870 * then x[0] = ((k / 31) << 5) + (k % 31).
871 * -- x[1], x[2]... contain the value in little-endian order, 31
872 * bits per word (x[1] contains the least significant 31 bits).
873 * The upper bit of each word is 0.
874 *
875 * Multiplications rely on the elementary 32x32->64 multiplication.
876 *
877 * The announced bit length specifies the number of bits that are
878 * significant in the subsequent 32-bit words. Unused bits in the
879 * last (most significant) word are set to 0; subsequent words are
880 * uninitialized and need not exist at all.
881 *
882 * The execution time and memory access patterns of all computations
883 * depend on the announced bit length, but not on the actual word
884 * values. For modular integers, the announced bit length of any integer
885 * modulo n is equal to the actual bit length of n; thus, computations
886 * on modular integers are "constant-time" (only the modulus length may
887 * leak).
888 */
889
890 /*
891 * Test whether an integer is zero.
892 */
893 uint32_t br_i31_iszero(const uint32_t *x);
894
895 /*
896 * Add b[] to a[] and return the carry (0 or 1). If ctl is 0, then a[]
897 * is unmodified, but the carry is still computed and returned. The
898 * arrays a[] and b[] MUST have the same announced bit length.
899 *
900 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
901 */
902 uint32_t br_i31_add(uint32_t *a, const uint32_t *b, uint32_t ctl);
903
904 /*
905 * Subtract b[] from a[] and return the carry (0 or 1). If ctl is 0,
906 * then a[] is unmodified, but the carry is still computed and returned.
907 * The arrays a[] and b[] MUST have the same announced bit length.
908 *
909 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
910 */
911 uint32_t br_i31_sub(uint32_t *a, const uint32_t *b, uint32_t ctl);
912
913 /*
914 * Compute the ENCODED actual bit length of an integer. The argument x
915 * should point to the first (least significant) value word of the
916 * integer. The len 'xlen' contains the number of 32-bit words to
917 * access. The upper bit of each value word MUST be 0.
918 * Returned value is ((k / 31) << 5) + (k % 31) if the bit length is k.
919 *
920 * CT: value or length of x does not leak.
921 */
922 uint32_t br_i31_bit_length(uint32_t *x, size_t xlen);
923
924 /*
925 * Decode an integer from its big-endian unsigned representation. The
926 * "true" bit length of the integer is computed and set in the encoded
927 * announced bit length (x[0]), but all words of x[] corresponding to
928 * the full 'len' bytes of the source are set.
929 *
930 * CT: value or length of x does not leak.
931 */
932 void br_i31_decode(uint32_t *x, const void *src, size_t len);
933
934 /*
935 * Decode an integer from its big-endian unsigned representation. The
936 * integer MUST be lower than m[]; the (encoded) announced bit length
937 * written in x[] will be equal to that of m[]. All 'len' bytes from the
938 * source are read.
939 *
940 * Returned value is 1 if the decode value fits within the modulus, 0
941 * otherwise. In the latter case, the x[] buffer will be set to 0 (but
942 * still with the announced bit length of m[]).
943 *
944 * CT: value or length of x does not leak. Memory access pattern depends
945 * only of 'len' and the announced bit length of m. Whether x fits or
946 * not does not leak either.
947 */
948 uint32_t br_i31_decode_mod(uint32_t *x,
949 const void *src, size_t len, const uint32_t *m);
950
951 /*
952 * Zeroize an integer. The announced bit length is set to the provided
953 * value, and the corresponding words are set to 0. The ENCODED bit length
954 * is expected here.
955 */
956 static inline void
957 br_i31_zero(uint32_t *x, uint32_t bit_len)
958 {
959 *x ++ = bit_len;
960 memset(x, 0, ((bit_len + 31) >> 5) * sizeof *x);
961 }
962
963 /*
964 * Right-shift an integer. The shift amount must be lower than 31
965 * bits.
966 */
967 void br_i31_rshift(uint32_t *x, int count);
968
969 /*
970 * Reduce an integer (a[]) modulo another (m[]). The result is written
971 * in x[] and its announced bit length is set to be equal to that of m[].
972 *
973 * x[] MUST be distinct from a[] and m[].
974 *
975 * CT: only announced bit lengths leak, not values of x, a or m.
976 */
977 void br_i31_reduce(uint32_t *x, const uint32_t *a, const uint32_t *m);
978
979 /*
980 * Decode an integer from its big-endian unsigned representation, and
981 * reduce it modulo the provided modulus m[]. The announced bit length
982 * of the result is set to be equal to that of the modulus.
983 *
984 * x[] MUST be distinct from m[].
985 */
986 void br_i31_decode_reduce(uint32_t *x,
987 const void *src, size_t len, const uint32_t *m);
988
989 /*
990 * Multiply x[] by 2^31 and then add integer z, modulo m[]. This
991 * function assumes that x[] and m[] have the same announced bit
992 * length, the announced bit length of m[] matches its true
993 * bit length.
994 *
995 * x[] and m[] MUST be distinct arrays. z MUST fit in 31 bits (upper
996 * bit set to 0).
997 *
998 * CT: only the common announced bit length of x and m leaks, not
999 * the values of x, z or m.
1000 */
1001 void br_i31_muladd_small(uint32_t *x, uint32_t z, const uint32_t *m);
1002
1003 /*
1004 * Encode an integer into its big-endian unsigned representation. The
1005 * output length in bytes is provided (parameter 'len'); if the length
1006 * is too short then the integer is appropriately truncated; if it is
1007 * too long then the extra bytes are set to 0.
1008 */
1009 void br_i31_encode(void *dst, size_t len, const uint32_t *x);
1010
1011 /*
1012 * Compute -(1/x) mod 2^31. If x is even, then this function returns 0.
1013 */
1014 uint32_t br_i31_ninv31(uint32_t x);
1015
1016 /*
1017 * Compute a modular Montgomery multiplication. d[] is filled with the
1018 * value of x*y/R modulo m[] (where R is the Montgomery factor). The
1019 * array d[] MUST be distinct from x[], y[] and m[]. x[] and y[] MUST be
1020 * numerically lower than m[]. x[] and y[] MAY be the same array. The
1021 * "m0i" parameter is equal to -(1/m0) mod 2^31, where m0 is the least
1022 * significant value word of m[] (this works only if m[] is an odd
1023 * integer).
1024 */
1025 void br_i31_montymul(uint32_t *d, const uint32_t *x, const uint32_t *y,
1026 const uint32_t *m, uint32_t m0i);
1027
1028 /*
1029 * Convert a modular integer to Montgomery representation. The integer x[]
1030 * MUST be lower than m[], but with the same announced bit length.
1031 */
1032 void br_i31_to_monty(uint32_t *x, const uint32_t *m);
1033
1034 /*
1035 * Convert a modular integer back from Montgomery representation. The
1036 * integer x[] MUST be lower than m[], but with the same announced bit
1037 * length. The "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is
1038 * the least significant value word of m[] (this works only if m[] is
1039 * an odd integer).
1040 */
1041 void br_i31_from_monty(uint32_t *x, const uint32_t *m, uint32_t m0i);
1042
1043 /*
1044 * Compute a modular exponentiation. x[] MUST be an integer modulo m[]
1045 * (same announced bit length, lower value). m[] MUST be odd. The
1046 * exponent is in big-endian unsigned notation, over 'elen' bytes. The
1047 * "m0i" parameter is equal to -(1/m0) mod 2^31, where m0 is the least
1048 * significant value word of m[] (this works only if m[] is an odd
1049 * integer). The t1[] and t2[] parameters must be temporary arrays,
1050 * each large enough to accommodate an integer with the same size as m[].
1051 */
1052 void br_i31_modpow(uint32_t *x, const unsigned char *e, size_t elen,
1053 const uint32_t *m, uint32_t m0i, uint32_t *t1, uint32_t *t2);
1054
1055 /*
1056 * Compute d+a*b, result in d. The initial announced bit length of d[]
1057 * MUST match that of a[]. The d[] array MUST be large enough to
1058 * accommodate the full result, plus (possibly) an extra word. The
1059 * resulting announced bit length of d[] will be the sum of the announced
1060 * bit lengths of a[] and b[] (therefore, it may be larger than the actual
1061 * bit length of the numerical result).
1062 *
1063 * a[] and b[] may be the same array. d[] must be disjoint from both a[]
1064 * and b[].
1065 */
1066 void br_i31_mulacc(uint32_t *d, const uint32_t *a, const uint32_t *b);
1067
1068 /* ==================================================================== */
1069
1070 static inline void
1071 br_i15_zero(uint16_t *x, uint16_t bit_len)
1072 {
1073 *x ++ = bit_len;
1074 memset(x, 0, ((bit_len + 15) >> 4) * sizeof *x);
1075 }
1076
1077 uint32_t br_i15_iszero(const uint16_t *x);
1078
1079 uint16_t br_i15_ninv15(uint16_t x);
1080
1081 uint32_t br_i15_add(uint16_t *a, const uint16_t *b, uint32_t ctl);
1082
1083 uint32_t br_i15_sub(uint16_t *a, const uint16_t *b, uint32_t ctl);
1084
1085 void br_i15_muladd_small(uint16_t *x, uint16_t z, const uint16_t *m);
1086
1087 void br_i15_montymul(uint16_t *d, const uint16_t *x, const uint16_t *y,
1088 const uint16_t *m, uint16_t m0i);
1089
1090 void br_i15_to_monty(uint16_t *x, const uint16_t *m);
1091
1092 void br_i15_modpow(uint16_t *x, const unsigned char *e, size_t elen,
1093 const uint16_t *m, uint16_t m0i, uint16_t *t1, uint16_t *t2);
1094
1095 void br_i15_encode(void *dst, size_t len, const uint16_t *x);
1096
1097 uint32_t br_i15_decode_mod(uint16_t *x,
1098 const void *src, size_t len, const uint16_t *m);
1099
1100 void br_i15_rshift(uint16_t *x, int count);
1101
1102 uint32_t br_i15_bit_length(uint16_t *x, size_t xlen);
1103
1104 void br_i15_decode(uint16_t *x, const void *src, size_t len);
1105
1106 void br_i15_from_monty(uint16_t *x, const uint16_t *m, uint16_t m0i);
1107
1108 void br_i15_decode_reduce(uint16_t *x,
1109 const void *src, size_t len, const uint16_t *m);
1110
1111 void br_i15_reduce(uint16_t *x, const uint16_t *a, const uint16_t *m);
1112
1113 void br_i15_mulacc(uint16_t *d, const uint16_t *a, const uint16_t *b);
1114
1115 /* ==================================================================== */
1116
1117 static inline size_t
1118 br_digest_size(const br_hash_class *digest_class)
1119 {
1120 return (size_t)(digest_class->desc >> BR_HASHDESC_OUT_OFF)
1121 & BR_HASHDESC_OUT_MASK;
1122 }
1123
1124 /*
1125 * Get the output size (in bytes) of a hash function.
1126 */
1127 size_t br_digest_size_by_ID(int digest_id);
1128
1129 /*
1130 * Get the OID (encoded OBJECT IDENTIFIER value, without tag and length)
1131 * for a hash function. If digest_id is not a supported digest identifier
1132 * (in particular if it is equal to 0, i.e. br_md5sha1_ID), then NULL is
1133 * returned and *len is set to 0.
1134 */
1135 const unsigned char *br_digest_OID(int digest_id, size_t *len);
1136
1137 /* ==================================================================== */
1138 /*
1139 * DES support functions.
1140 */
1141
1142 /*
1143 * Apply DES Initial Permutation.
1144 */
1145 void br_des_do_IP(uint32_t *xl, uint32_t *xr);
1146
1147 /*
1148 * Apply DES Final Permutation (inverse of IP).
1149 */
1150 void br_des_do_invIP(uint32_t *xl, uint32_t *xr);
1151
1152 /*
1153 * Key schedule unit: for a DES key (8 bytes), compute 16 subkeys. Each
1154 * subkey is two 28-bit words represented as two 32-bit words; the PC-2
1155 * bit extration is NOT applied.
1156 */
1157 void br_des_keysched_unit(uint32_t *skey, const void *key);
1158
1159 /*
1160 * Reversal of 16 DES sub-keys (for decryption).
1161 */
1162 void br_des_rev_skey(uint32_t *skey);
1163
1164 /*
1165 * DES/3DES key schedule for 'des_tab' (encryption direction). Returned
1166 * value is the number of rounds.
1167 */
1168 unsigned br_des_tab_keysched(uint32_t *skey, const void *key, size_t key_len);
1169
1170 /*
1171 * DES/3DES key schedule for 'des_ct' (encryption direction). Returned
1172 * value is the number of rounds.
1173 */
1174 unsigned br_des_ct_keysched(uint32_t *skey, const void *key, size_t key_len);
1175
1176 /*
1177 * DES/3DES subkey decompression (from the compressed bitsliced subkeys).
1178 */
1179 void br_des_ct_skey_expand(uint32_t *sk_exp,
1180 unsigned num_rounds, const uint32_t *skey);
1181
1182 /*
1183 * DES/3DES block encryption/decryption ('des_tab').
1184 */
1185 void br_des_tab_process_block(unsigned num_rounds,
1186 const uint32_t *skey, void *block);
1187
1188 /*
1189 * DES/3DES block encryption/decryption ('des_ct').
1190 */
1191 void br_des_ct_process_block(unsigned num_rounds,
1192 const uint32_t *skey, void *block);
1193
1194 /* ==================================================================== */
1195 /*
1196 * AES support functions.
1197 */
1198
1199 /*
1200 * The AES S-box (256-byte table).
1201 */
1202 extern const unsigned char br_aes_S[];
1203
1204 /*
1205 * AES key schedule. skey[] is filled with n+1 128-bit subkeys, where n
1206 * is the number of rounds (10 to 14, depending on key size). The number
1207 * of rounds is returned. If the key size is invalid (not 16, 24 or 32),
1208 * then 0 is returned.
1209 *
1210 * This implementation uses a 256-byte table and is NOT constant-time.
1211 */
1212 unsigned br_aes_keysched(uint32_t *skey, const void *key, size_t key_len);
1213
1214 /*
1215 * AES key schedule for decryption ('aes_big' implementation).
1216 */
1217 unsigned br_aes_big_keysched_inv(uint32_t *skey,
1218 const void *key, size_t key_len);
1219
1220 /*
1221 * AES block encryption with the 'aes_big' implementation (fast, but
1222 * not constant-time). This function encrypts a single block "in place".
1223 */
1224 void br_aes_big_encrypt(unsigned num_rounds, const uint32_t *skey, void *data);
1225
1226 /*
1227 * AES block decryption with the 'aes_big' implementation (fast, but
1228 * not constant-time). This function decrypts a single block "in place".
1229 */
1230 void br_aes_big_decrypt(unsigned num_rounds, const uint32_t *skey, void *data);
1231
1232 /*
1233 * AES block encryption with the 'aes_small' implementation (small, but
1234 * slow and not constant-time). This function encrypts a single block
1235 * "in place".
1236 */
1237 void br_aes_small_encrypt(unsigned num_rounds,
1238 const uint32_t *skey, void *data);
1239
1240 /*
1241 * AES block decryption with the 'aes_small' implementation (small, but
1242 * slow and not constant-time). This function decrypts a single block
1243 * "in place".
1244 */
1245 void br_aes_small_decrypt(unsigned num_rounds,
1246 const uint32_t *skey, void *data);
1247
1248 /*
1249 * The constant-time implementation is "bitsliced": the 128-bit state is
1250 * split over eight 32-bit words q* in the following way:
1251 *
1252 * -- Input block consists in 16 bytes:
1253 * a00 a10 a20 a30 a01 a11 a21 a31 a02 a12 a22 a32 a03 a13 a23 a33
1254 * In the terminology of FIPS 197, this is a 4x4 matrix which is read
1255 * column by column.
1256 *
1257 * -- Each byte is split into eight bits which are distributed over the
1258 * eight words, at the same rank. Thus, for a byte x at rank k, bit 0
1259 * (least significant) of x will be at rank k in q0 (if that bit is b,
1260 * then it contributes "b << k" to the value of q0), bit 1 of x will be
1261 * at rank k in q1, and so on.
1262 *
1263 * -- Ranks given to bits are in "row order" and are either all even, or
1264 * all odd. Two independent AES states are thus interleaved, one using
1265 * the even ranks, the other the odd ranks. Row order means:
1266 * a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23 a30 a31 a32 a33
1267 *
1268 * Converting input bytes from two AES blocks to bitslice representation
1269 * is done in the following way:
1270 * -- Decode first block into the four words q0 q2 q4 q6, in that order,
1271 * using little-endian convention.
1272 * -- Decode second block into the four words q1 q3 q5 q7, in that order,
1273 * using little-endian convention.
1274 * -- Call br_aes_ct_ortho().
1275 *
1276 * Converting back to bytes is done by using the reverse operations. Note
1277 * that br_aes_ct_ortho() is its own inverse.
1278 */
1279
1280 /*
1281 * Perform bytewise orthogonalization of eight 32-bit words. Bytes
1282 * of q0..q7 are spread over all words: for a byte x that occurs
1283 * at rank i in q[j] (byte x uses bits 8*i to 8*i+7 in q[j]), the bit
1284 * of rank k in x (0 <= k <= 7) goes to q[k] at rank 8*i+j.
1285 *
1286 * This operation is an involution.
1287 */
1288 void br_aes_ct_ortho(uint32_t *q);
1289
1290 /*
1291 * The AES S-box, as a bitsliced constant-time version. The input array
1292 * consists in eight 32-bit words; 32 S-box instances are computed in
1293 * parallel. Bits 0 to 7 of each S-box input (bit 0 is least significant)
1294 * are spread over the words 0 to 7, at the same rank.
1295 */
1296 void br_aes_ct_bitslice_Sbox(uint32_t *q);
1297
1298 /*
1299 * Like br_aes_bitslice_Sbox(), but for the inverse S-box.
1300 */
1301 void br_aes_ct_bitslice_invSbox(uint32_t *q);
1302
1303 /*
1304 * Compute AES encryption on bitsliced data. Since input is stored on
1305 * eight 32-bit words, two block encryptions are actually performed
1306 * in parallel.
1307 */
1308 void br_aes_ct_bitslice_encrypt(unsigned num_rounds,
1309 const uint32_t *skey, uint32_t *q);
1310
1311 /*
1312 * Compute AES decryption on bitsliced data. Since input is stored on
1313 * eight 32-bit words, two block decryptions are actually performed
1314 * in parallel.
1315 */
1316 void br_aes_ct_bitslice_decrypt(unsigned num_rounds,
1317 const uint32_t *skey, uint32_t *q);
1318
1319 /*
1320 * AES key schedule, constant-time version. skey[] is filled with n+1
1321 * 128-bit subkeys, where n is the number of rounds (10 to 14, depending
1322 * on key size). The number of rounds is returned. If the key size is
1323 * invalid (not 16, 24 or 32), then 0 is returned.
1324 */
1325 unsigned br_aes_ct_keysched(uint32_t *comp_skey,
1326 const void *key, size_t key_len);
1327
1328 /*
1329 * Expand AES subkeys as produced by br_aes_ct_keysched(), into
1330 * a larger array suitable for br_aes_ct_bitslice_encrypt() and
1331 * br_aes_ct_bitslice_decrypt().
1332 */
1333 void br_aes_ct_skey_expand(uint32_t *skey,
1334 unsigned num_rounds, const uint32_t *comp_skey);
1335
1336 /*
1337 * For the ct64 implementation, the same bitslicing technique is used,
1338 * but four instances are interleaved. First instance uses bits 0, 4,
1339 * 8, 12,... of each word; second instance uses bits 1, 5, 9, 13,...
1340 * and so on.
1341 */
1342
1343 /*
1344 * Perform bytewise orthogonalization of eight 64-bit words. Bytes
1345 * of q0..q7 are spread over all words: for a byte x that occurs
1346 * at rank i in q[j] (byte x uses bits 8*i to 8*i+7 in q[j]), the bit
1347 * of rank k in x (0 <= k <= 7) goes to q[k] at rank 8*i+j.
1348 *
1349 * This operation is an involution.
1350 */
1351 void br_aes_ct64_ortho(uint64_t *q);
1352
1353 /*
1354 * Interleave bytes for an AES input block. If input bytes are
1355 * denoted 0123456789ABCDEF, and have been decoded with little-endian
1356 * convention (w[0] contains 0123, with '3' being most significant;
1357 * w[1] contains 4567, and so on), then output word q0 will be
1358 * set to 08192A3B (again little-endian convention) and q1 will
1359 * be set to 4C5D6E7F.
1360 */
1361 void br_aes_ct64_interleave_in(uint64_t *q0, uint64_t *q1, const uint32_t *w);
1362
1363 /*
1364 * Perform the opposite of br_aes_ct64_interleave_in().
1365 */
1366 void br_aes_ct64_interleave_out(uint32_t *w, uint64_t q0, uint64_t q1);
1367
1368 /*
1369 * The AES S-box, as a bitsliced constant-time version. The input array
1370 * consists in eight 64-bit words; 64 S-box instances are computed in
1371 * parallel. Bits 0 to 7 of each S-box input (bit 0 is least significant)
1372 * are spread over the words 0 to 7, at the same rank.
1373 */
1374 void br_aes_ct64_bitslice_Sbox(uint64_t *q);
1375
1376 /*
1377 * Like br_aes_bitslice_Sbox(), but for the inverse S-box.
1378 */
1379 void br_aes_ct64_bitslice_invSbox(uint64_t *q);
1380
1381 /*
1382 * Compute AES encryption on bitsliced data. Since input is stored on
1383 * eight 64-bit words, four block encryptions are actually performed
1384 * in parallel.
1385 */
1386 void br_aes_ct64_bitslice_encrypt(unsigned num_rounds,
1387 const uint64_t *skey, uint64_t *q);
1388
1389 /*
1390 * Compute AES decryption on bitsliced data. Since input is stored on
1391 * eight 64-bit words, four block decryptions are actually performed
1392 * in parallel.
1393 */
1394 void br_aes_ct64_bitslice_decrypt(unsigned num_rounds,
1395 const uint64_t *skey, uint64_t *q);
1396
1397 /*
1398 * AES key schedule, constant-time version. skey[] is filled with n+1
1399 * 128-bit subkeys, where n is the number of rounds (10 to 14, depending
1400 * on key size). The number of rounds is returned. If the key size is
1401 * invalid (not 16, 24 or 32), then 0 is returned.
1402 */
1403 unsigned br_aes_ct64_keysched(uint64_t *comp_skey,
1404 const void *key, size_t key_len);
1405
1406 /*
1407 * Expand AES subkeys as produced by br_aes_ct64_keysched(), into
1408 * a larger array suitable for br_aes_ct64_bitslice_encrypt() and
1409 * br_aes_ct64_bitslice_decrypt().
1410 */
1411 void br_aes_ct64_skey_expand(uint64_t *skey,
1412 unsigned num_rounds, const uint64_t *comp_skey);
1413
1414 /* ==================================================================== */
1415 /*
1416 * RSA.
1417 */
1418
1419 /*
1420 * Apply proper PKCS#1 v1.5 padding (for signatures). 'hash_oid' is
1421 * the encoded hash function OID, or NULL.
1422 */
1423 uint32_t br_rsa_pkcs1_sig_pad(const unsigned char *hash_oid,
1424 const unsigned char *hash, size_t hash_len,
1425 uint32_t n_bitlen, unsigned char *x);
1426
1427 /*
1428 * Check PKCS#1 v1.5 padding (for signatures). 'hash_oid' is the encoded
1429 * hash function OID, or NULL. The provided 'sig' value is _after_ the
1430 * modular exponentiation, i.e. it should be the padded hash. On
1431 * success, the hashed message is extracted.
1432 */
1433 uint32_t br_rsa_pkcs1_sig_unpad(const unsigned char *sig, size_t sig_len,
1434 const unsigned char *hash_oid, size_t hash_len,
1435 unsigned char *hash_out);
1436
1437 /* ==================================================================== */
1438 /*
1439 * Elliptic curves.
1440 */
1441
1442 /*
1443 * Type for generic EC parameters: curve order (unsigned big-endian
1444 * encoding) and encoded conventional generator.
1445 */
1446 typedef struct {
1447 int curve;
1448 const unsigned char *order;
1449 size_t order_len;
1450 const unsigned char *generator;
1451 size_t generator_len;
1452 } br_ec_curve_def;
1453
1454 extern const br_ec_curve_def br_secp256r1;
1455 extern const br_ec_curve_def br_secp384r1;
1456 extern const br_ec_curve_def br_secp521r1;
1457
1458 #if 0
1459 /* obsolete */
1460 /*
1461 * Type for the parameters for a "prime curve":
1462 * coordinates are in GF(p), with p prime
1463 * curve equation is Y^2 = X^3 - 3*X + b
1464 * b is in Montgomery representation
1465 * curve order is n and is prime
1466 * base point is G (encoded) and has order n
1467 */
1468 typedef struct {
1469 const uint32_t *p;
1470 const uint32_t *b;
1471 const uint32_t p0i;
1472 } br_ec_prime_i31_curve;
1473
1474 extern const br_ec_prime_i31_curve br_ec_prime_i31_secp256r1;
1475 extern const br_ec_prime_i31_curve br_ec_prime_i31_secp384r1;
1476 extern const br_ec_prime_i31_curve br_ec_prime_i31_secp521r1;
1477
1478 #define BR_EC_I31_LEN ((BR_MAX_EC_SIZE + 61) / 31)
1479 #endif
1480
1481 /*
1482 * Decode some bytes as an i31 integer, with truncation (corresponding
1483 * to the 'bits2int' operation in RFC 6979). The target ENCODED bit
1484 * length is provided as last parameter. The resulting value will have
1485 * this declared bit length, and consists the big-endian unsigned decoding
1486 * of exactly that many bits in the source (capped at the source length).
1487 */
1488 void br_ecdsa_i31_bits2int(uint32_t *x,
1489 const void *src, size_t len, uint32_t ebitlen);
1490
1491 /*
1492 * Decode some bytes as an i15 integer, with truncation (corresponding
1493 * to the 'bits2int' operation in RFC 6979). The target ENCODED bit
1494 * length is provided as last parameter. The resulting value will have
1495 * this declared bit length, and consists the big-endian unsigned decoding
1496 * of exactly that many bits in the source (capped at the source length).
1497 */
1498 void br_ecdsa_i15_bits2int(uint16_t *x,
1499 const void *src, size_t len, uint32_t ebitlen);
1500
1501 /* ==================================================================== */
1502 /*
1503 * SSL/TLS support functions.
1504 */
1505
1506 /*
1507 * Record types.
1508 */
1509 #define BR_SSL_CHANGE_CIPHER_SPEC 20
1510 #define BR_SSL_ALERT 21
1511 #define BR_SSL_HANDSHAKE 22
1512 #define BR_SSL_APPLICATION_DATA 23
1513
1514 /*
1515 * Handshake message types.
1516 */
1517 #define BR_SSL_HELLO_REQUEST 0
1518 #define BR_SSL_CLIENT_HELLO 1
1519 #define BR_SSL_SERVER_HELLO 2
1520 #define BR_SSL_CERTIFICATE 11
1521 #define BR_SSL_SERVER_KEY_EXCHANGE 12
1522 #define BR_SSL_CERTIFICATE_REQUEST 13
1523 #define BR_SSL_SERVER_HELLO_DONE 14
1524 #define BR_SSL_CERTIFICATE_VERIFY 15
1525 #define BR_SSL_CLIENT_KEY_EXCHANGE 16
1526 #define BR_SSL_FINISHED 20
1527
1528 /*
1529 * Alert levels.
1530 */
1531 #define BR_LEVEL_WARNING 1
1532 #define BR_LEVEL_FATAL 2
1533
1534 /*
1535 * Low-level I/O state.
1536 */
1537 #define BR_IO_FAILED 0
1538 #define BR_IO_IN 1
1539 #define BR_IO_OUT 2
1540 #define BR_IO_INOUT 3
1541
1542 /*
1543 * Mark a SSL engine as failed. The provided error code is recorded if
1544 * the engine was not already marked as failed. If 'err' is 0, then the
1545 * engine is marked as closed (without error).
1546 */
1547 void br_ssl_engine_fail(br_ssl_engine_context *cc, int err);
1548
1549 /*
1550 * Test whether the engine is closed (normally or as a failure).
1551 */
1552 static inline int
1553 br_ssl_engine_closed(const br_ssl_engine_context *cc)
1554 {
1555 return cc->iomode == BR_IO_FAILED;
1556 }
1557
1558 /*
1559 * Configure a new maximum fragment length. If possible, the maximum
1560 * length for outgoing records is immediately adjusted (if there are
1561 * not already too many buffered bytes for that).
1562 */
1563 void br_ssl_engine_new_max_frag_len(
1564 br_ssl_engine_context *rc, unsigned max_frag_len);
1565
1566 /*
1567 * Test whether the current incoming record has been fully received
1568 * or not. This functions returns 0 only if a complete record header
1569 * has been received, but some of the (possibly encrypted) payload
1570 * has not yet been obtained.
1571 */
1572 int br_ssl_engine_recvrec_finished(const br_ssl_engine_context *rc);
1573
1574 /*
1575 * Flush the current record (if not empty). This is meant to be called
1576 * from the handshake processor only.
1577 */
1578 void br_ssl_engine_flush_record(br_ssl_engine_context *cc);
1579
1580 /*
1581 * Test whether there is some accumulated payload to send.
1582 */
1583 static inline int
1584 br_ssl_engine_has_pld_to_send(const br_ssl_engine_context *rc)
1585 {
1586 return rc->oxa != rc->oxb && rc->oxa != rc->oxc;
1587 }
1588
1589 /*
1590 * Initialize RNG in engine. Returned value is 1 on success, 0 on error.
1591 * This function will try to use the OS-provided RNG, if available. If
1592 * there is no OS-provided RNG, or if it failed, and no entropy was
1593 * injected by the caller, then a failure will be reported. On error,
1594 * the context error code is set.
1595 */
1596 int br_ssl_engine_init_rand(br_ssl_engine_context *cc);
1597
1598 /*
1599 * Reset the handshake-related parts of the engine.
1600 */
1601 void br_ssl_engine_hs_reset(br_ssl_engine_context *cc,
1602 void (*hsinit)(void *), void (*hsrun)(void *));
1603
1604 /*
1605 * Get the PRF to use for this context, for the provided PRF hash
1606 * function ID.
1607 */
1608 br_tls_prf_impl br_ssl_engine_get_PRF(br_ssl_engine_context *cc, int prf_id);
1609
1610 /*
1611 * Consume the provided pre-master secret and compute the corresponding
1612 * master secret. The 'prf_id' is the ID of the hash function to use
1613 * with the TLS 1.2 PRF (ignored if the version is TLS 1.0 or 1.1).
1614 */
1615 void br_ssl_engine_compute_master(br_ssl_engine_context *cc,
1616 int prf_id, const void *pms, size_t len);
1617
1618 /*
1619 * Switch to CBC decryption for incoming records.
1620 * cc the engine context
1621 * is_client non-zero for a client, zero for a server
1622 * prf_id id of hash function for PRF (ignored if not TLS 1.2+)
1623 * mac_id id of hash function for HMAC
1624 * bc_impl block cipher implementation (CBC decryption)
1625 * cipher_key_len block cipher key length (in bytes)
1626 */
1627 void br_ssl_engine_switch_cbc_in(br_ssl_engine_context *cc,
1628 int is_client, int prf_id, int mac_id,
1629 const br_block_cbcdec_class *bc_impl, size_t cipher_key_len);
1630
1631 /*
1632 * Switch to CBC encryption for outgoing records.
1633 * cc the engine context
1634 * is_client non-zero for a client, zero for a server
1635 * prf_id id of hash function for PRF (ignored if not TLS 1.2+)
1636 * mac_id id of hash function for HMAC
1637 * bc_impl block cipher implementation (CBC encryption)
1638 * cipher_key_len block cipher key length (in bytes)
1639 */
1640 void br_ssl_engine_switch_cbc_out(br_ssl_engine_context *cc,
1641 int is_client, int prf_id, int mac_id,
1642 const br_block_cbcenc_class *bc_impl, size_t cipher_key_len);
1643
1644 /*
1645 * Switch to GCM decryption for incoming records.
1646 * cc the engine context
1647 * is_client non-zero for a client, zero for a server
1648 * prf_id id of hash function for PRF
1649 * bc_impl block cipher implementation (CTR)
1650 * cipher_key_len block cipher key length (in bytes)
1651 */
1652 void br_ssl_engine_switch_gcm_in(br_ssl_engine_context *cc,
1653 int is_client, int prf_id,
1654 const br_block_ctr_class *bc_impl, size_t cipher_key_len);
1655
1656 /*
1657 * Switch to GCM encryption for outgoing records.
1658 * cc the engine context
1659 * is_client non-zero for a client, zero for a server
1660 * prf_id id of hash function for PRF
1661 * bc_impl block cipher implementation (CTR)
1662 * cipher_key_len block cipher key length (in bytes)
1663 */
1664 void br_ssl_engine_switch_gcm_out(br_ssl_engine_context *cc,
1665 int is_client, int prf_id,
1666 const br_block_ctr_class *bc_impl, size_t cipher_key_len);
1667
1668 /*
1669 * Switch to ChaCha20+Poly1305 decryption for incoming records.
1670 * cc the engine context
1671 * is_client non-zero for a client, zero for a server
1672 * prf_id id of hash function for PRF
1673 */
1674 void br_ssl_engine_switch_chapol_in(br_ssl_engine_context *cc,
1675 int is_client, int prf_id);
1676
1677 /*
1678 * Switch to ChaCha20+Poly1305 encryption for outgoing records.
1679 * cc the engine context
1680 * is_client non-zero for a client, zero for a server
1681 * prf_id id of hash function for PRF
1682 */
1683 void br_ssl_engine_switch_chapol_out(br_ssl_engine_context *cc,
1684 int is_client, int prf_id);
1685
1686 /*
1687 * Calls to T0-generated code.
1688 */
1689 void br_ssl_hs_client_init_main(void *ctx);
1690 void br_ssl_hs_client_run(void *ctx);
1691 void br_ssl_hs_server_init_main(void *ctx);
1692 void br_ssl_hs_server_run(void *ctx);
1693
1694 /*
1695 * Get the hash function to use for signatures, given a bit mask of
1696 * supported hash functions. This implements a strict choice order
1697 * (namely SHA-256, SHA-384, SHA-512, SHA-224, SHA-1). If the mask
1698 * does not document support of any of these hash functions, then this
1699 * functions returns 0.
1700 */
1701 int br_ssl_choose_hash(unsigned bf);
1702
1703 /* ==================================================================== */
1704
1705 #endif