3830c7c5b916d95a4301a4ffc1e65b4fe278486e
[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 * On MSVC, disable the warning about applying unary minus on an
36 * unsigned type: it is standard, we do it all the time, and for
37 * good reasons.
38 */
39 #if _MSC_VER
40 #pragma warning( disable : 4146 )
41 #endif
42
43 /*
44 * Maximum size for a RSA modulus (in bits). Allocated stack buffers
45 * depend on that size, so this value should be kept small. Currently,
46 * 2048-bit RSA keys offer adequate security, and should still do so for
47 * the next few decades; however, a number of widespread PKI have
48 * already set their root keys to RSA-4096, so we should be able to
49 * process such keys.
50 *
51 * This value MUST be a multiple of 64.
52 */
53 #define BR_MAX_RSA_SIZE 4096
54
55 /*
56 * Maximum size for a RSA factor (in bits). This is for RSA private-key
57 * operations. Default is to support factors up to a bit more than half
58 * the maximum modulus size.
59 *
60 * This value MUST be a multiple of 32.
61 */
62 #define BR_MAX_RSA_FACTOR ((BR_MAX_RSA_SIZE + 64) >> 1)
63
64 /*
65 * Maximum size for an EC curve (modulus or order), in bits. Size of
66 * stack buffers depends on that parameter. This size MUST be a multiple
67 * of 8 (so that decoding an integer with that many bytes does not
68 * overflow).
69 */
70 #define BR_MAX_EC_SIZE 528
71
72 /*
73 * Some macros to recognize the current architecture. Right now, we are
74 * interested into automatically recognizing architecture with efficient
75 * 64-bit types so that we may automatically use implementations that
76 * use 64-bit registers in that case. Future versions may detect, e.g.,
77 * availability of SSE2 intrinsics.
78 *
79 * If 'unsigned long' is a 64-bit type, then we assume that 64-bit types
80 * are efficient. Otherwise, we rely on macros that depend on compiler,
81 * OS and architecture. In any case, failure to detect the architecture
82 * as 64-bit means that the 32-bit code will be used, and that code
83 * works also on 64-bit architectures (the 64-bit code may simply be
84 * more efficient).
85 *
86 * The test on 'unsigned long' should already catch most cases, the one
87 * notable exception being Windows code where 'unsigned long' is kept to
88 * 32-bit for compatbility with all the legacy code that liberally uses
89 * the 'DWORD' type for 32-bit values.
90 *
91 * Macro names are taken from: http://nadeausoftware.com/articles/2012/02/c_c_tip_how_detect_processor_type_using_compiler_predefined_macros
92 */
93 #ifndef BR_64
94 #if ((ULONG_MAX >> 31) >> 31) == 3
95 #define BR_64 1
96 #elif defined(__ia64) || defined(__itanium__) || defined(_M_IA64)
97 #define BR_64 1
98 #elif defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) \
99 || defined(__64BIT__) || defined(_LP64) || defined(__LP64__)
100 #define BR_64 1
101 #elif defined(__sparc64__)
102 #define BR_64 1
103 #elif defined(__x86_64__) || defined(_M_X64)
104 #define BR_64 1
105 #endif
106 #endif
107
108 /*
109 * Set BR_LOMUL on platforms where it makes sense.
110 */
111 #ifndef BR_LOMUL
112 #if BR_ARMEL_CORTEX_GCC
113 #define BR_LOMUL 1
114 #endif
115 #endif
116
117 /*
118 * Determine whether x86 AES instructions are understood by the compiler.
119 */
120 #ifndef BR_AES_X86NI
121 #if (__i386__ || __x86_64__) \
122 && ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) \
123 || (__clang_major__ > 3 \
124 || (__clang_major__ == 3 && __clang_minor__ >= 7)))
125 #define BR_AES_X86NI 1
126 #elif (_M_IX86 || _M_X64) && (_MSC_VER >= 1700)
127 #define BR_AES_X86NI 1
128 #endif
129 #endif
130
131 /*
132 * If we use x86 AES instruction, determine the compiler brand.
133 */
134 #if BR_AES_X86NI
135 #ifndef BR_AES_X86NI_GCC
136 #if __GNUC__
137 #define BR_AES_X86NI_GCC 1
138 #endif
139 #endif
140 #ifndef BR_AES_X86NI_MSC
141 #if _MSC_VER >= 1700
142 #define BR_AES_X86NI_MSC 1
143 #endif
144 #endif
145 #endif
146
147 /*
148 * A macro to tag a function with a "target" attribute (for GCC and Clang).
149 */
150 #if BR_AES_X86NI_GCC
151 #define BR_TARGET(x) __attribute__((target(x)))
152 #else
153 #define BR_TARGET(x)
154 #endif
155
156 /*
157 * GCC versions from 4.4 to 4.8 (inclusive) must use a special #pragma
158 * to activate extra opcodes before including the relevant intrinsic
159 * headers. But these don't work with Clang (which does not need them
160 * either). We also need that #pragma for GCC 4.9 in order to work
161 * around a compiler bug (it tends to blow up on ghash_pclmul code
162 * otherwise).
163 */
164 #if BR_AES_X86NI_GCC && !defined BR_AES_X86NI_GCC_OLD
165 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 4 && __GNUC_MINOR__ <= 9 && !__clang__
166 #define BR_AES_X86NI_GCC_OLD 1
167 #endif
168 #endif
169
170 /*
171 * POWER8 crypto support. We rely on compiler macros for the
172 * architecture, since we do not have a reliable, simple way to detect
173 * the required support at runtime (we could try running an opcode, and
174 * trapping the exception or signal on illegal instruction, but this
175 * induces some non-trivial OS dependencies that we would prefer to
176 * avoid if possible).
177 */
178 #ifndef BR_POWER8
179 #if __GNUC__ && ((_ARCH_PWR8 || _ARCH_PPC) && __CRYPTO__)
180 #define BR_POWER8 1
181 #endif
182 #endif
183
184 /*
185 * Detect endinanness on POWER8.
186 */
187 #if BR_POWER8
188 #if defined BR_POWER8_LE
189 #undef BR_POWER8_BE
190 #if BR_POWER8_LE
191 #define BR_POWER8_BE 0
192 #else
193 #define BR_POWER8_BE 1
194 #endif
195 #elif defined BR_POWER8_BE
196 #undef BR_POWER8_LE
197 #if BR_POWER8_BE
198 #define BR_POWER8_LE 0
199 #else
200 #define BR_POWER8_LE 1
201 #endif
202 #else
203 #if __LITTLE_ENDIAN__
204 #define BR_POWER8_LE 1
205 #define BR_POWER8_BE 0
206 #else
207 #define BR_POWER8_LE 0
208 #define BR_POWER8_BE 1
209 #endif
210 #endif
211 #endif
212
213 /*
214 * Detect support for 128-bit integers.
215 */
216 #if !defined BR_INT128 && !defined BR_UMUL128
217 #ifdef __SIZEOF_INT128__
218 #define BR_INT128 1
219 #elif _M_X64
220 #define BR_UMUL128 1
221 #endif
222 #endif
223
224 /*
225 * Detect support for unaligned accesses with known endianness.
226 *
227 * x86 (both 32-bit and 64-bit) is little-endian and allows unaligned
228 * accesses.
229 *
230 * POWER/PowerPC allows unaligned accesses when big-endian. POWER8 and
231 * later also allow unaligned accesses when little-endian.
232 */
233 #if !defined BR_LE_UNALIGNED && !defined BR_BE_UNALIGNED
234
235 #if __i386 || __i386__ || __x86_64__ || _M_IX86 || _M_X64
236 #define BR_LE_UNALIGNED 1
237 #elif BR_POWER8_BE
238 #define BR_BE_UNALIGNED 1
239 #elif BR_POWER8_LE
240 #define BR_LE_UNALIGNED 1
241 #elif (__powerpc__ || __powerpc64__ || _M_PPC || _ARCH_PPC || _ARCH_PPC64) \
242 && __BIG_ENDIAN__
243 #define BR_BE_UNALIGNED 1
244 #endif
245
246 #endif
247
248 /* ==================================================================== */
249 /*
250 * Encoding/decoding functions.
251 *
252 * 32-bit and 64-bit decoding, both little-endian and big-endian, is
253 * implemented with the inline functions below.
254 *
255 * When allowed by some compile-time options (autodetected or provided),
256 * optimised code is used, to perform direct memory access when the
257 * underlying architecture supports it, both for endianness and
258 * alignment. This, however, may trigger strict aliasing issues; the
259 * code below uses unions to perform (supposedly) safe type punning.
260 * Since the C aliasing rules are relatively complex and were amended,
261 * or at least re-explained with different phrasing, in all successive
262 * versions of the C standard, it is always a bit risky to bet that any
263 * specific version of a C compiler got it right, for some notion of
264 * "right".
265 */
266
267 typedef union {
268 uint16_t u;
269 unsigned char b[sizeof(uint16_t)];
270 } br_union_u16;
271
272 typedef union {
273 uint32_t u;
274 unsigned char b[sizeof(uint32_t)];
275 } br_union_u32;
276
277 typedef union {
278 uint64_t u;
279 unsigned char b[sizeof(uint64_t)];
280 } br_union_u64;
281
282 static inline void
283 br_enc16le(void *dst, unsigned x)
284 {
285 #if BR_LE_UNALIGNED
286 ((br_union_u16 *)dst)->u = x;
287 #else
288 unsigned char *buf;
289
290 buf = dst;
291 buf[0] = (unsigned char)x;
292 buf[1] = (unsigned char)(x >> 8);
293 #endif
294 }
295
296 static inline void
297 br_enc16be(void *dst, unsigned x)
298 {
299 #if BR_BE_UNALIGNED
300 ((br_union_u16 *)dst)->u = x;
301 #else
302 unsigned char *buf;
303
304 buf = dst;
305 buf[0] = (unsigned char)(x >> 8);
306 buf[1] = (unsigned char)x;
307 #endif
308 }
309
310 static inline unsigned
311 br_dec16le(const void *src)
312 {
313 #if BR_LE_UNALIGNED
314 return ((const br_union_u16 *)src)->u;
315 #else
316 const unsigned char *buf;
317
318 buf = src;
319 return (unsigned)buf[0] | ((unsigned)buf[1] << 8);
320 #endif
321 }
322
323 static inline unsigned
324 br_dec16be(const void *src)
325 {
326 #if BR_BE_UNALIGNED
327 return ((const br_union_u16 *)src)->u;
328 #else
329 const unsigned char *buf;
330
331 buf = src;
332 return ((unsigned)buf[0] << 8) | (unsigned)buf[1];
333 #endif
334 }
335
336 static inline void
337 br_enc32le(void *dst, uint32_t x)
338 {
339 #if BR_LE_UNALIGNED
340 ((br_union_u32 *)dst)->u = x;
341 #else
342 unsigned char *buf;
343
344 buf = dst;
345 buf[0] = (unsigned char)x;
346 buf[1] = (unsigned char)(x >> 8);
347 buf[2] = (unsigned char)(x >> 16);
348 buf[3] = (unsigned char)(x >> 24);
349 #endif
350 }
351
352 static inline void
353 br_enc32be(void *dst, uint32_t x)
354 {
355 #if BR_BE_UNALIGNED
356 ((br_union_u32 *)dst)->u = x;
357 #else
358 unsigned char *buf;
359
360 buf = dst;
361 buf[0] = (unsigned char)(x >> 24);
362 buf[1] = (unsigned char)(x >> 16);
363 buf[2] = (unsigned char)(x >> 8);
364 buf[3] = (unsigned char)x;
365 #endif
366 }
367
368 static inline uint32_t
369 br_dec32le(const void *src)
370 {
371 #if BR_LE_UNALIGNED
372 return ((const br_union_u32 *)src)->u;
373 #else
374 const unsigned char *buf;
375
376 buf = src;
377 return (uint32_t)buf[0]
378 | ((uint32_t)buf[1] << 8)
379 | ((uint32_t)buf[2] << 16)
380 | ((uint32_t)buf[3] << 24);
381 #endif
382 }
383
384 static inline uint32_t
385 br_dec32be(const void *src)
386 {
387 #if BR_BE_UNALIGNED
388 return ((const br_union_u32 *)src)->u;
389 #else
390 const unsigned char *buf;
391
392 buf = src;
393 return ((uint32_t)buf[0] << 24)
394 | ((uint32_t)buf[1] << 16)
395 | ((uint32_t)buf[2] << 8)
396 | (uint32_t)buf[3];
397 #endif
398 }
399
400 static inline void
401 br_enc64le(void *dst, uint64_t x)
402 {
403 #if BR_LE_UNALIGNED
404 ((br_union_u64 *)dst)->u = x;
405 #else
406 unsigned char *buf;
407
408 buf = dst;
409 br_enc32le(buf, (uint32_t)x);
410 br_enc32le(buf + 4, (uint32_t)(x >> 32));
411 #endif
412 }
413
414 static inline void
415 br_enc64be(void *dst, uint64_t x)
416 {
417 #if BR_BE_UNALIGNED
418 ((br_union_u64 *)dst)->u = x;
419 #else
420 unsigned char *buf;
421
422 buf = dst;
423 br_enc32be(buf, (uint32_t)(x >> 32));
424 br_enc32be(buf + 4, (uint32_t)x);
425 #endif
426 }
427
428 static inline uint64_t
429 br_dec64le(const void *src)
430 {
431 #if BR_LE_UNALIGNED
432 return ((const br_union_u64 *)src)->u;
433 #else
434 const unsigned char *buf;
435
436 buf = src;
437 return (uint64_t)br_dec32le(buf)
438 | ((uint64_t)br_dec32le(buf + 4) << 32);
439 #endif
440 }
441
442 static inline uint64_t
443 br_dec64be(const void *src)
444 {
445 #if BR_BE_UNALIGNED
446 return ((const br_union_u64 *)src)->u;
447 #else
448 const unsigned char *buf;
449
450 buf = src;
451 return ((uint64_t)br_dec32be(buf) << 32)
452 | (uint64_t)br_dec32be(buf + 4);
453 #endif
454 }
455
456 /*
457 * Range decoding and encoding (for several successive values).
458 */
459 void br_range_dec16le(uint16_t *v, size_t num, const void *src);
460 void br_range_dec16be(uint16_t *v, size_t num, const void *src);
461 void br_range_enc16le(void *dst, const uint16_t *v, size_t num);
462 void br_range_enc16be(void *dst, const uint16_t *v, size_t num);
463
464 void br_range_dec32le(uint32_t *v, size_t num, const void *src);
465 void br_range_dec32be(uint32_t *v, size_t num, const void *src);
466 void br_range_enc32le(void *dst, const uint32_t *v, size_t num);
467 void br_range_enc32be(void *dst, const uint32_t *v, size_t num);
468
469 void br_range_dec64le(uint64_t *v, size_t num, const void *src);
470 void br_range_dec64be(uint64_t *v, size_t num, const void *src);
471 void br_range_enc64le(void *dst, const uint64_t *v, size_t num);
472 void br_range_enc64be(void *dst, const uint64_t *v, size_t num);
473
474 /*
475 * Byte-swap a 32-bit integer.
476 */
477 static inline uint32_t
478 br_swap32(uint32_t x)
479 {
480 x = ((x & (uint32_t)0x00FF00FF) << 8)
481 | ((x >> 8) & (uint32_t)0x00FF00FF);
482 return (x << 16) | (x >> 16);
483 }
484
485 /* ==================================================================== */
486 /*
487 * Support code for hash functions.
488 */
489
490 /*
491 * IV for MD5, SHA-1, SHA-224 and SHA-256.
492 */
493 extern const uint32_t br_md5_IV[];
494 extern const uint32_t br_sha1_IV[];
495 extern const uint32_t br_sha224_IV[];
496 extern const uint32_t br_sha256_IV[];
497
498 /*
499 * Round functions for MD5, SHA-1, SHA-224 and SHA-256 (SHA-224 and
500 * SHA-256 use the same round function).
501 */
502 void br_md5_round(const unsigned char *buf, uint32_t *val);
503 void br_sha1_round(const unsigned char *buf, uint32_t *val);
504 void br_sha2small_round(const unsigned char *buf, uint32_t *val);
505
506 /*
507 * The core function for the TLS PRF. It computes
508 * P_hash(secret, label + seed), and XORs the result into the dst buffer.
509 */
510 void br_tls_phash(void *dst, size_t len,
511 const br_hash_class *dig,
512 const void *secret, size_t secret_len,
513 const char *label, const void *seed, size_t seed_len);
514
515 /*
516 * Copy all configured hash implementations from a multihash context
517 * to another.
518 */
519 static inline void
520 br_multihash_copyimpl(br_multihash_context *dst,
521 const br_multihash_context *src)
522 {
523 memcpy((void *)dst->impl, src->impl, sizeof src->impl);
524 }
525
526 /* ==================================================================== */
527 /*
528 * Constant-time primitives. These functions manipulate 32-bit values in
529 * order to provide constant-time comparisons and multiplexers.
530 *
531 * Boolean values (the "ctl" bits) MUST have value 0 or 1.
532 *
533 * Implementation notes:
534 * =====================
535 *
536 * The uintN_t types are unsigned and with width exactly N bits; the C
537 * standard guarantees that computations are performed modulo 2^N, and
538 * there can be no overflow. Negation (unary '-') works on unsigned types
539 * as well.
540 *
541 * The intN_t types are guaranteed to have width exactly N bits, with no
542 * padding bit, and using two's complement representation. Casting
543 * intN_t to uintN_t really is conversion modulo 2^N. Beware that intN_t
544 * types, being signed, trigger implementation-defined behaviour on
545 * overflow (including raising some signal): with GCC, while modular
546 * arithmetics are usually applied, the optimizer may assume that
547 * overflows don't occur (unless the -fwrapv command-line option is
548 * added); Clang has the additional -ftrapv option to explicitly trap on
549 * integer overflow or underflow.
550 */
551
552 /*
553 * Negate a boolean.
554 */
555 static inline uint32_t
556 NOT(uint32_t ctl)
557 {
558 return ctl ^ 1;
559 }
560
561 /*
562 * Multiplexer: returns x if ctl == 1, y if ctl == 0.
563 */
564 static inline uint32_t
565 MUX(uint32_t ctl, uint32_t x, uint32_t y)
566 {
567 return y ^ (-ctl & (x ^ y));
568 }
569
570 /*
571 * Equality check: returns 1 if x == y, 0 otherwise.
572 */
573 static inline uint32_t
574 EQ(uint32_t x, uint32_t y)
575 {
576 uint32_t q;
577
578 q = x ^ y;
579 return NOT((q | -q) >> 31);
580 }
581
582 /*
583 * Inequality check: returns 1 if x != y, 0 otherwise.
584 */
585 static inline uint32_t
586 NEQ(uint32_t x, uint32_t y)
587 {
588 uint32_t q;
589
590 q = x ^ y;
591 return (q | -q) >> 31;
592 }
593
594 /*
595 * Comparison: returns 1 if x > y, 0 otherwise.
596 */
597 static inline uint32_t
598 GT(uint32_t x, uint32_t y)
599 {
600 /*
601 * If both x < 2^31 and x < 2^31, then y-x will have its high
602 * bit set if x > y, cleared otherwise.
603 *
604 * If either x >= 2^31 or y >= 2^31 (but not both), then the
605 * result is the high bit of x.
606 *
607 * If both x >= 2^31 and y >= 2^31, then we can virtually
608 * subtract 2^31 from both, and we are back to the first case.
609 * Since (y-2^31)-(x-2^31) = y-x, the subtraction is already
610 * fine.
611 */
612 uint32_t z;
613
614 z = y - x;
615 return (z ^ ((x ^ y) & (x ^ z))) >> 31;
616 }
617
618 /*
619 * Other comparisons (greater-or-equal, lower-than, lower-or-equal).
620 */
621 #define GE(x, y) NOT(GT(y, x))
622 #define LT(x, y) GT(y, x)
623 #define LE(x, y) NOT(GT(x, y))
624
625 /*
626 * General comparison: returned value is -1, 0 or 1, depending on
627 * whether x is lower than, equal to, or greater than y.
628 */
629 static inline int32_t
630 CMP(uint32_t x, uint32_t y)
631 {
632 return (int32_t)GT(x, y) | -(int32_t)GT(y, x);
633 }
634
635 /*
636 * Returns 1 if x == 0, 0 otherwise. Take care that the operand is signed.
637 */
638 static inline uint32_t
639 EQ0(int32_t x)
640 {
641 uint32_t q;
642
643 q = (uint32_t)x;
644 return ~(q | -q) >> 31;
645 }
646
647 /*
648 * Returns 1 if x > 0, 0 otherwise. Take care that the operand is signed.
649 */
650 static inline uint32_t
651 GT0(int32_t x)
652 {
653 /*
654 * High bit of -x is 0 if x == 0, but 1 if x > 0.
655 */
656 uint32_t q;
657
658 q = (uint32_t)x;
659 return (~q & -q) >> 31;
660 }
661
662 /*
663 * Returns 1 if x >= 0, 0 otherwise. Take care that the operand is signed.
664 */
665 static inline uint32_t
666 GE0(int32_t x)
667 {
668 return ~(uint32_t)x >> 31;
669 }
670
671 /*
672 * Returns 1 if x < 0, 0 otherwise. Take care that the operand is signed.
673 */
674 static inline uint32_t
675 LT0(int32_t x)
676 {
677 return (uint32_t)x >> 31;
678 }
679
680 /*
681 * Returns 1 if x <= 0, 0 otherwise. Take care that the operand is signed.
682 */
683 static inline uint32_t
684 LE0(int32_t x)
685 {
686 uint32_t q;
687
688 /*
689 * ~-x has its high bit set if and only if -x is nonnegative (as
690 * a signed int), i.e. x is in the -(2^31-1) to 0 range. We must
691 * do an OR with x itself to account for x = -2^31.
692 */
693 q = (uint32_t)x;
694 return (q | ~-q) >> 31;
695 }
696
697 /*
698 * Conditional copy: src[] is copied into dst[] if and only if ctl is 1.
699 * dst[] and src[] may overlap completely (but not partially).
700 */
701 void br_ccopy(uint32_t ctl, void *dst, const void *src, size_t len);
702
703 #define CCOPY br_ccopy
704
705 /*
706 * Compute the bit length of a 32-bit integer. Returned value is between 0
707 * and 32 (inclusive).
708 */
709 static inline uint32_t
710 BIT_LENGTH(uint32_t x)
711 {
712 uint32_t k, c;
713
714 k = NEQ(x, 0);
715 c = GT(x, 0xFFFF); x = MUX(c, x >> 16, x); k += c << 4;
716 c = GT(x, 0x00FF); x = MUX(c, x >> 8, x); k += c << 3;
717 c = GT(x, 0x000F); x = MUX(c, x >> 4, x); k += c << 2;
718 c = GT(x, 0x0003); x = MUX(c, x >> 2, x); k += c << 1;
719 k += GT(x, 0x0001);
720 return k;
721 }
722
723 /*
724 * Compute the minimum of x and y.
725 */
726 static inline uint32_t
727 MIN(uint32_t x, uint32_t y)
728 {
729 return MUX(GT(x, y), y, x);
730 }
731
732 /*
733 * Compute the maximum of x and y.
734 */
735 static inline uint32_t
736 MAX(uint32_t x, uint32_t y)
737 {
738 return MUX(GT(x, y), x, y);
739 }
740
741 /*
742 * Multiply two 32-bit integers, with a 64-bit result. This default
743 * implementation assumes that the basic multiplication operator
744 * yields constant-time code.
745 */
746 #define MUL(x, y) ((uint64_t)(x) * (uint64_t)(y))
747
748 #if BR_CT_MUL31
749
750 /*
751 * Alternate implementation of MUL31, that will be constant-time on some
752 * (old) platforms where the default MUL31 is not. Unfortunately, it is
753 * also substantially slower, and yields larger code, on more modern
754 * platforms, which is why it is deactivated by default.
755 *
756 * MUL31_lo() must do some extra work because on some platforms, the
757 * _signed_ multiplication may return early if the top bits are 1.
758 * Simply truncating (casting) the output of MUL31() would not be
759 * sufficient, because the compiler may notice that we keep only the low
760 * word, and then replace automatically the unsigned multiplication with
761 * a signed multiplication opcode.
762 */
763 #define MUL31(x, y) ((uint64_t)((x) | (uint32_t)0x80000000) \
764 * (uint64_t)((y) | (uint32_t)0x80000000) \
765 - ((uint64_t)(x) << 31) - ((uint64_t)(y) << 31) \
766 - ((uint64_t)1 << 62))
767 static inline uint32_t
768 MUL31_lo(uint32_t x, uint32_t y)
769 {
770 uint32_t xl, xh;
771 uint32_t yl, yh;
772
773 xl = (x & 0xFFFF) | (uint32_t)0x80000000;
774 xh = (x >> 16) | (uint32_t)0x80000000;
775 yl = (y & 0xFFFF) | (uint32_t)0x80000000;
776 yh = (y >> 16) | (uint32_t)0x80000000;
777 return (xl * yl + ((xl * yh + xh * yl) << 16)) & (uint32_t)0x7FFFFFFF;
778 }
779
780 #else
781
782 /*
783 * Multiply two 31-bit integers, with a 62-bit result. This default
784 * implementation assumes that the basic multiplication operator
785 * yields constant-time code.
786 * The MUL31_lo() macro returns only the low 31 bits of the product.
787 */
788 #define MUL31(x, y) ((uint64_t)(x) * (uint64_t)(y))
789 #define MUL31_lo(x, y) (((uint32_t)(x) * (uint32_t)(y)) & (uint32_t)0x7FFFFFFF)
790
791 #endif
792
793 /*
794 * Multiply two words together; the sum of the lengths of the two
795 * operands must not exceed 31 (for instance, one operand may use 16
796 * bits if the other fits on 15). If BR_CT_MUL15 is non-zero, then the
797 * macro will contain some extra operations that help in making the
798 * operation constant-time on some platforms, where the basic 32-bit
799 * multiplication is not constant-time.
800 */
801 #if BR_CT_MUL15
802 #define MUL15(x, y) (((uint32_t)(x) | (uint32_t)0x80000000) \
803 * ((uint32_t)(y) | (uint32_t)0x80000000) \
804 & (uint32_t)0x7FFFFFFF)
805 #else
806 #define MUL15(x, y) ((uint32_t)(x) * (uint32_t)(y))
807 #endif
808
809 /*
810 * Arithmetic right shift (sign bit is copied). What happens when
811 * right-shifting a negative value is _implementation-defined_, so it
812 * does not trigger undefined behaviour, but it is still up to each
813 * compiler to define (and document) what it does. Most/all compilers
814 * will do an arithmetic shift, the sign bit being used to fill the
815 * holes; this is a native operation on the underlying CPU, and it would
816 * make little sense for the compiler to do otherwise. GCC explicitly
817 * documents that it follows that convention.
818 *
819 * Still, if BR_NO_ARITH_SHIFT is defined (and non-zero), then an
820 * alternate version will be used, that does not rely on such
821 * implementation-defined behaviour. Unfortunately, it is also slower
822 * and yields bigger code, which is why it is deactivated by default.
823 */
824 #if BR_NO_ARITH_SHIFT
825 #define ARSH(x, n) (((uint32_t)(x) >> (n)) \
826 | ((-((uint32_t)(x) >> 31)) << (32 - (n))))
827 #else
828 #define ARSH(x, n) ((*(int32_t *)&(x)) >> (n))
829 #endif
830
831 /*
832 * Constant-time division. The dividend hi:lo is divided by the
833 * divisor d; the quotient is returned and the remainder is written
834 * in *r. If hi == d, then the quotient does not fit on 32 bits;
835 * returned value is thus truncated. If hi > d, returned values are
836 * indeterminate.
837 */
838 uint32_t br_divrem(uint32_t hi, uint32_t lo, uint32_t d, uint32_t *r);
839
840 /*
841 * Wrapper for br_divrem(); the remainder is returned, and the quotient
842 * is discarded.
843 */
844 static inline uint32_t
845 br_rem(uint32_t hi, uint32_t lo, uint32_t d)
846 {
847 uint32_t r;
848
849 br_divrem(hi, lo, d, &r);
850 return r;
851 }
852
853 /*
854 * Wrapper for br_divrem(); the quotient is returned, and the remainder
855 * is discarded.
856 */
857 static inline uint32_t
858 br_div(uint32_t hi, uint32_t lo, uint32_t d)
859 {
860 uint32_t r;
861
862 return br_divrem(hi, lo, d, &r);
863 }
864
865 /* ==================================================================== */
866
867 /*
868 * Integers 'i32'
869 * --------------
870 *
871 * The 'i32' functions implement computations on big integers using
872 * an internal representation as an array of 32-bit integers. For
873 * an array x[]:
874 * -- x[0] contains the "announced bit length" of the integer
875 * -- x[1], x[2]... contain the value in little-endian order (x[1]
876 * contains the least significant 32 bits)
877 *
878 * Multiplications rely on the elementary 32x32->64 multiplication.
879 *
880 * The announced bit length specifies the number of bits that are
881 * significant in the subsequent 32-bit words. Unused bits in the
882 * last (most significant) word are set to 0; subsequent words are
883 * uninitialized and need not exist at all.
884 *
885 * The execution time and memory access patterns of all computations
886 * depend on the announced bit length, but not on the actual word
887 * values. For modular integers, the announced bit length of any integer
888 * modulo n is equal to the actual bit length of n; thus, computations
889 * on modular integers are "constant-time" (only the modulus length may
890 * leak).
891 */
892
893 /*
894 * Compute the actual bit length of an integer. The argument x should
895 * point to the first (least significant) value word of the integer.
896 * The len 'xlen' contains the number of 32-bit words to access.
897 *
898 * CT: value or length of x does not leak.
899 */
900 uint32_t br_i32_bit_length(uint32_t *x, size_t xlen);
901
902 /*
903 * Decode an integer from its big-endian unsigned representation. The
904 * "true" bit length of the integer is computed, but all words of x[]
905 * corresponding to the full 'len' bytes of the source are set.
906 *
907 * CT: value or length of x does not leak.
908 */
909 void br_i32_decode(uint32_t *x, const void *src, size_t len);
910
911 /*
912 * Decode an integer from its big-endian unsigned representation. The
913 * integer MUST be lower than m[]; the announced bit length written in
914 * x[] will be equal to that of m[]. All 'len' bytes from the source are
915 * read.
916 *
917 * Returned value is 1 if the decode value fits within the modulus, 0
918 * otherwise. In the latter case, the x[] buffer will be set to 0 (but
919 * still with the announced bit length of m[]).
920 *
921 * CT: value or length of x does not leak. Memory access pattern depends
922 * only of 'len' and the announced bit length of m. Whether x fits or
923 * not does not leak either.
924 */
925 uint32_t br_i32_decode_mod(uint32_t *x,
926 const void *src, size_t len, const uint32_t *m);
927
928 /*
929 * Reduce an integer (a[]) modulo another (m[]). The result is written
930 * in x[] and its announced bit length is set to be equal to that of m[].
931 *
932 * x[] MUST be distinct from a[] and m[].
933 *
934 * CT: only announced bit lengths leak, not values of x, a or m.
935 */
936 void br_i32_reduce(uint32_t *x, const uint32_t *a, const uint32_t *m);
937
938 /*
939 * Decode an integer from its big-endian unsigned representation, and
940 * reduce it modulo the provided modulus m[]. The announced bit length
941 * of the result is set to be equal to that of the modulus.
942 *
943 * x[] MUST be distinct from m[].
944 */
945 void br_i32_decode_reduce(uint32_t *x,
946 const void *src, size_t len, const uint32_t *m);
947
948 /*
949 * Encode an integer into its big-endian unsigned representation. The
950 * output length in bytes is provided (parameter 'len'); if the length
951 * is too short then the integer is appropriately truncated; if it is
952 * too long then the extra bytes are set to 0.
953 */
954 void br_i32_encode(void *dst, size_t len, const uint32_t *x);
955
956 /*
957 * Multiply x[] by 2^32 and then add integer z, modulo m[]. This
958 * function assumes that x[] and m[] have the same announced bit
959 * length, and the announced bit length of m[] matches its true
960 * bit length.
961 *
962 * x[] and m[] MUST be distinct arrays.
963 *
964 * CT: only the common announced bit length of x and m leaks, not
965 * the values of x, z or m.
966 */
967 void br_i32_muladd_small(uint32_t *x, uint32_t z, const uint32_t *m);
968
969 /*
970 * Extract one word from an integer. The offset is counted in bits.
971 * The word MUST entirely fit within the word elements corresponding
972 * to the announced bit length of a[].
973 */
974 static inline uint32_t
975 br_i32_word(const uint32_t *a, uint32_t off)
976 {
977 size_t u;
978 unsigned j;
979
980 u = (size_t)(off >> 5) + 1;
981 j = (unsigned)off & 31;
982 if (j == 0) {
983 return a[u];
984 } else {
985 return (a[u] >> j) | (a[u + 1] << (32 - j));
986 }
987 }
988
989 /*
990 * Test whether an integer is zero.
991 */
992 uint32_t br_i32_iszero(const uint32_t *x);
993
994 /*
995 * Add b[] to a[] and return the carry (0 or 1). If ctl is 0, then a[]
996 * is unmodified, but the carry is still computed and returned. The
997 * arrays a[] and b[] MUST have the same announced bit length.
998 *
999 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
1000 */
1001 uint32_t br_i32_add(uint32_t *a, const uint32_t *b, uint32_t ctl);
1002
1003 /*
1004 * Subtract b[] from a[] and return the carry (0 or 1). If ctl is 0,
1005 * then a[] is unmodified, but the carry is still computed and returned.
1006 * The arrays a[] and b[] MUST have the same announced bit length.
1007 *
1008 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
1009 */
1010 uint32_t br_i32_sub(uint32_t *a, const uint32_t *b, uint32_t ctl);
1011
1012 /*
1013 * Compute d+a*b, result in d. The initial announced bit length of d[]
1014 * MUST match that of a[]. The d[] array MUST be large enough to
1015 * accommodate the full result, plus (possibly) an extra word. The
1016 * resulting announced bit length of d[] will be the sum of the announced
1017 * bit lengths of a[] and b[] (therefore, it may be larger than the actual
1018 * bit length of the numerical result).
1019 *
1020 * a[] and b[] may be the same array. d[] must be disjoint from both a[]
1021 * and b[].
1022 */
1023 void br_i32_mulacc(uint32_t *d, const uint32_t *a, const uint32_t *b);
1024
1025 /*
1026 * Zeroize an integer. The announced bit length is set to the provided
1027 * value, and the corresponding words are set to 0.
1028 */
1029 static inline void
1030 br_i32_zero(uint32_t *x, uint32_t bit_len)
1031 {
1032 *x ++ = bit_len;
1033 memset(x, 0, ((bit_len + 31) >> 5) * sizeof *x);
1034 }
1035
1036 /*
1037 * Compute -(1/x) mod 2^32. If x is even, then this function returns 0.
1038 */
1039 uint32_t br_i32_ninv32(uint32_t x);
1040
1041 /*
1042 * Convert a modular integer to Montgomery representation. The integer x[]
1043 * MUST be lower than m[], but with the same announced bit length.
1044 */
1045 void br_i32_to_monty(uint32_t *x, const uint32_t *m);
1046
1047 /*
1048 * Convert a modular integer back from Montgomery representation. The
1049 * integer x[] MUST be lower than m[], but with the same announced bit
1050 * length. The "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is
1051 * the least significant value word of m[] (this works only if m[] is
1052 * an odd integer).
1053 */
1054 void br_i32_from_monty(uint32_t *x, const uint32_t *m, uint32_t m0i);
1055
1056 /*
1057 * Compute a modular Montgomery multiplication. d[] is filled with the
1058 * value of x*y/R modulo m[] (where R is the Montgomery factor). The
1059 * array d[] MUST be distinct from x[], y[] and m[]. x[] and y[] MUST be
1060 * numerically lower than m[]. x[] and y[] MAY be the same array. The
1061 * "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is the least
1062 * significant value word of m[] (this works only if m[] is an odd
1063 * integer).
1064 */
1065 void br_i32_montymul(uint32_t *d, const uint32_t *x, const uint32_t *y,
1066 const uint32_t *m, uint32_t m0i);
1067
1068 /*
1069 * Compute a modular exponentiation. x[] MUST be an integer modulo m[]
1070 * (same announced bit length, lower value). m[] MUST be odd. The
1071 * exponent is in big-endian unsigned notation, over 'elen' bytes. The
1072 * "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is the least
1073 * significant value word of m[] (this works only if m[] is an odd
1074 * integer). The t1[] and t2[] parameters must be temporary arrays,
1075 * each large enough to accommodate an integer with the same size as m[].
1076 */
1077 void br_i32_modpow(uint32_t *x, const unsigned char *e, size_t elen,
1078 const uint32_t *m, uint32_t m0i, uint32_t *t1, uint32_t *t2);
1079
1080 /* ==================================================================== */
1081
1082 /*
1083 * Integers 'i31'
1084 * --------------
1085 *
1086 * The 'i31' functions implement computations on big integers using
1087 * an internal representation as an array of 32-bit integers. For
1088 * an array x[]:
1089 * -- x[0] encodes the array length and the "announced bit length"
1090 * of the integer: namely, if the announced bit length is k,
1091 * then x[0] = ((k / 31) << 5) + (k % 31).
1092 * -- x[1], x[2]... contain the value in little-endian order, 31
1093 * bits per word (x[1] contains the least significant 31 bits).
1094 * The upper bit of each word is 0.
1095 *
1096 * Multiplications rely on the elementary 32x32->64 multiplication.
1097 *
1098 * The announced bit length specifies the number of bits that are
1099 * significant in the subsequent 32-bit words. Unused bits in the
1100 * last (most significant) word are set to 0; subsequent words are
1101 * uninitialized and need not exist at all.
1102 *
1103 * The execution time and memory access patterns of all computations
1104 * depend on the announced bit length, but not on the actual word
1105 * values. For modular integers, the announced bit length of any integer
1106 * modulo n is equal to the actual bit length of n; thus, computations
1107 * on modular integers are "constant-time" (only the modulus length may
1108 * leak).
1109 */
1110
1111 /*
1112 * Test whether an integer is zero.
1113 */
1114 uint32_t br_i31_iszero(const uint32_t *x);
1115
1116 /*
1117 * Add b[] to a[] and return the carry (0 or 1). If ctl is 0, then a[]
1118 * is unmodified, but the carry is still computed and returned. The
1119 * arrays a[] and b[] MUST have the same announced bit length.
1120 *
1121 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
1122 */
1123 uint32_t br_i31_add(uint32_t *a, const uint32_t *b, uint32_t ctl);
1124
1125 /*
1126 * Subtract b[] from a[] and return the carry (0 or 1). If ctl is 0,
1127 * then a[] is unmodified, but the carry is still computed and returned.
1128 * The arrays a[] and b[] MUST have the same announced bit length.
1129 *
1130 * a[] and b[] MAY be the same array, but partial overlap is not allowed.
1131 */
1132 uint32_t br_i31_sub(uint32_t *a, const uint32_t *b, uint32_t ctl);
1133
1134 /*
1135 * Compute the ENCODED actual bit length of an integer. The argument x
1136 * should point to the first (least significant) value word of the
1137 * integer. The len 'xlen' contains the number of 32-bit words to
1138 * access. The upper bit of each value word MUST be 0.
1139 * Returned value is ((k / 31) << 5) + (k % 31) if the bit length is k.
1140 *
1141 * CT: value or length of x does not leak.
1142 */
1143 uint32_t br_i31_bit_length(uint32_t *x, size_t xlen);
1144
1145 /*
1146 * Decode an integer from its big-endian unsigned representation. The
1147 * "true" bit length of the integer is computed and set in the encoded
1148 * announced bit length (x[0]), but all words of x[] corresponding to
1149 * the full 'len' bytes of the source are set.
1150 *
1151 * CT: value or length of x does not leak.
1152 */
1153 void br_i31_decode(uint32_t *x, const void *src, size_t len);
1154
1155 /*
1156 * Decode an integer from its big-endian unsigned representation. The
1157 * integer MUST be lower than m[]; the (encoded) announced bit length
1158 * written in x[] will be equal to that of m[]. All 'len' bytes from the
1159 * source are read.
1160 *
1161 * Returned value is 1 if the decode value fits within the modulus, 0
1162 * otherwise. In the latter case, the x[] buffer will be set to 0 (but
1163 * still with the announced bit length of m[]).
1164 *
1165 * CT: value or length of x does not leak. Memory access pattern depends
1166 * only of 'len' and the announced bit length of m. Whether x fits or
1167 * not does not leak either.
1168 */
1169 uint32_t br_i31_decode_mod(uint32_t *x,
1170 const void *src, size_t len, const uint32_t *m);
1171
1172 /*
1173 * Zeroize an integer. The announced bit length is set to the provided
1174 * value, and the corresponding words are set to 0. The ENCODED bit length
1175 * is expected here.
1176 */
1177 static inline void
1178 br_i31_zero(uint32_t *x, uint32_t bit_len)
1179 {
1180 *x ++ = bit_len;
1181 memset(x, 0, ((bit_len + 31) >> 5) * sizeof *x);
1182 }
1183
1184 /*
1185 * Right-shift an integer. The shift amount must be lower than 31
1186 * bits.
1187 */
1188 void br_i31_rshift(uint32_t *x, int count);
1189
1190 /*
1191 * Reduce an integer (a[]) modulo another (m[]). The result is written
1192 * in x[] and its announced bit length is set to be equal to that of m[].
1193 *
1194 * x[] MUST be distinct from a[] and m[].
1195 *
1196 * CT: only announced bit lengths leak, not values of x, a or m.
1197 */
1198 void br_i31_reduce(uint32_t *x, const uint32_t *a, const uint32_t *m);
1199
1200 /*
1201 * Decode an integer from its big-endian unsigned representation, and
1202 * reduce it modulo the provided modulus m[]. The announced bit length
1203 * of the result is set to be equal to that of the modulus.
1204 *
1205 * x[] MUST be distinct from m[].
1206 */
1207 void br_i31_decode_reduce(uint32_t *x,
1208 const void *src, size_t len, const uint32_t *m);
1209
1210 /*
1211 * Multiply x[] by 2^31 and then add integer z, modulo m[]. This
1212 * function assumes that x[] and m[] have the same announced bit
1213 * length, the announced bit length of m[] matches its true
1214 * bit length.
1215 *
1216 * x[] and m[] MUST be distinct arrays. z MUST fit in 31 bits (upper
1217 * bit set to 0).
1218 *
1219 * CT: only the common announced bit length of x and m leaks, not
1220 * the values of x, z or m.
1221 */
1222 void br_i31_muladd_small(uint32_t *x, uint32_t z, const uint32_t *m);
1223
1224 /*
1225 * Encode an integer into its big-endian unsigned representation. The
1226 * output length in bytes is provided (parameter 'len'); if the length
1227 * is too short then the integer is appropriately truncated; if it is
1228 * too long then the extra bytes are set to 0.
1229 */
1230 void br_i31_encode(void *dst, size_t len, const uint32_t *x);
1231
1232 /*
1233 * Compute -(1/x) mod 2^31. If x is even, then this function returns 0.
1234 */
1235 uint32_t br_i31_ninv31(uint32_t x);
1236
1237 /*
1238 * Compute a modular Montgomery multiplication. d[] is filled with the
1239 * value of x*y/R modulo m[] (where R is the Montgomery factor). The
1240 * array d[] MUST be distinct from x[], y[] and m[]. x[] and y[] MUST be
1241 * numerically lower than m[]. x[] and y[] MAY be the same array. The
1242 * "m0i" parameter is equal to -(1/m0) mod 2^31, where m0 is the least
1243 * significant value word of m[] (this works only if m[] is an odd
1244 * integer).
1245 */
1246 void br_i31_montymul(uint32_t *d, const uint32_t *x, const uint32_t *y,
1247 const uint32_t *m, uint32_t m0i);
1248
1249 /*
1250 * Convert a modular integer to Montgomery representation. The integer x[]
1251 * MUST be lower than m[], but with the same announced bit length.
1252 */
1253 void br_i31_to_monty(uint32_t *x, const uint32_t *m);
1254
1255 /*
1256 * Convert a modular integer back from Montgomery representation. The
1257 * integer x[] MUST be lower than m[], but with the same announced bit
1258 * length. The "m0i" parameter is equal to -(1/m0) mod 2^32, where m0 is
1259 * the least significant value word of m[] (this works only if m[] is
1260 * an odd integer).
1261 */
1262 void br_i31_from_monty(uint32_t *x, const uint32_t *m, uint32_t m0i);
1263
1264 /*
1265 * Compute a modular exponentiation. x[] MUST be an integer modulo m[]
1266 * (same announced bit length, lower value). m[] MUST be odd. The
1267 * exponent is in big-endian unsigned notation, over 'elen' bytes. The
1268 * "m0i" parameter is equal to -(1/m0) mod 2^31, where m0 is the least
1269 * significant value word of m[] (this works only if m[] is an odd
1270 * integer). The t1[] and t2[] parameters must be temporary arrays,
1271 * each large enough to accommodate an integer with the same size as m[].
1272 */
1273 void br_i31_modpow(uint32_t *x, const unsigned char *e, size_t elen,
1274 const uint32_t *m, uint32_t m0i, uint32_t *t1, uint32_t *t2);
1275
1276 /*
1277 * Compute a modular exponentiation. x[] MUST be an integer modulo m[]
1278 * (same announced bit length, lower value). m[] MUST be odd. The
1279 * exponent is in big-endian unsigned notation, over 'elen' bytes. The
1280 * "m0i" parameter is equal to -(1/m0) mod 2^31, where m0 is the least
1281 * significant value word of m[] (this works only if m[] is an odd
1282 * integer). The tmp[] array is used for temporaries, and has size
1283 * 'twlen' words; it must be large enough to accommodate at least two
1284 * temporary values with the same size as m[] (including the leading
1285 * "bit length" word). If there is room for more temporaries, then this
1286 * function may use the extra room for window-based optimisation,
1287 * resulting in faster computations.
1288 *
1289 * Returned value is 1 on success, 0 on error. An error is reported if
1290 * the provided tmp[] array is too short.
1291 */
1292 uint32_t br_i31_modpow_opt(uint32_t *x, const unsigned char *e, size_t elen,
1293 const uint32_t *m, uint32_t m0i, uint32_t *tmp, size_t twlen);
1294
1295 /*
1296 * Compute d+a*b, result in d. The initial announced bit length of d[]
1297 * MUST match that of a[]. The d[] array MUST be large enough to
1298 * accommodate the full result, plus (possibly) an extra word. The
1299 * resulting announced bit length of d[] will be the sum of the announced
1300 * bit lengths of a[] and b[] (therefore, it may be larger than the actual
1301 * bit length of the numerical result).
1302 *
1303 * a[] and b[] may be the same array. d[] must be disjoint from both a[]
1304 * and b[].
1305 */
1306 void br_i31_mulacc(uint32_t *d, const uint32_t *a, const uint32_t *b);
1307
1308 /* ==================================================================== */
1309
1310 /*
1311 * FIXME: document "i15" functions.
1312 */
1313
1314 static inline void
1315 br_i15_zero(uint16_t *x, uint16_t bit_len)
1316 {
1317 *x ++ = bit_len;
1318 memset(x, 0, ((bit_len + 15) >> 4) * sizeof *x);
1319 }
1320
1321 uint32_t br_i15_iszero(const uint16_t *x);
1322
1323 uint16_t br_i15_ninv15(uint16_t x);
1324
1325 uint32_t br_i15_add(uint16_t *a, const uint16_t *b, uint32_t ctl);
1326
1327 uint32_t br_i15_sub(uint16_t *a, const uint16_t *b, uint32_t ctl);
1328
1329 void br_i15_muladd_small(uint16_t *x, uint16_t z, const uint16_t *m);
1330
1331 void br_i15_montymul(uint16_t *d, const uint16_t *x, const uint16_t *y,
1332 const uint16_t *m, uint16_t m0i);
1333
1334 void br_i15_to_monty(uint16_t *x, const uint16_t *m);
1335
1336 void br_i15_modpow(uint16_t *x, const unsigned char *e, size_t elen,
1337 const uint16_t *m, uint16_t m0i, uint16_t *t1, uint16_t *t2);
1338
1339 uint32_t br_i15_modpow_opt(uint16_t *x, const unsigned char *e, size_t elen,
1340 const uint16_t *m, uint16_t m0i, uint16_t *tmp, size_t twlen);
1341
1342 void br_i15_encode(void *dst, size_t len, const uint16_t *x);
1343
1344 uint32_t br_i15_decode_mod(uint16_t *x,
1345 const void *src, size_t len, const uint16_t *m);
1346
1347 void br_i15_rshift(uint16_t *x, int count);
1348
1349 uint32_t br_i15_bit_length(uint16_t *x, size_t xlen);
1350
1351 void br_i15_decode(uint16_t *x, const void *src, size_t len);
1352
1353 void br_i15_from_monty(uint16_t *x, const uint16_t *m, uint16_t m0i);
1354
1355 void br_i15_decode_reduce(uint16_t *x,
1356 const void *src, size_t len, const uint16_t *m);
1357
1358 void br_i15_reduce(uint16_t *x, const uint16_t *a, const uint16_t *m);
1359
1360 void br_i15_mulacc(uint16_t *d, const uint16_t *a, const uint16_t *b);
1361
1362 uint32_t br_i62_modpow_opt(uint32_t *x31, const unsigned char *e, size_t elen,
1363 const uint32_t *m31, uint32_t m0i31, uint64_t *tmp, size_t twlen);
1364
1365 /* ==================================================================== */
1366
1367 static inline size_t
1368 br_digest_size(const br_hash_class *digest_class)
1369 {
1370 return (size_t)(digest_class->desc >> BR_HASHDESC_OUT_OFF)
1371 & BR_HASHDESC_OUT_MASK;
1372 }
1373
1374 /*
1375 * Get the output size (in bytes) of a hash function.
1376 */
1377 size_t br_digest_size_by_ID(int digest_id);
1378
1379 /*
1380 * Get the OID (encoded OBJECT IDENTIFIER value, without tag and length)
1381 * for a hash function. If digest_id is not a supported digest identifier
1382 * (in particular if it is equal to 0, i.e. br_md5sha1_ID), then NULL is
1383 * returned and *len is set to 0.
1384 */
1385 const unsigned char *br_digest_OID(int digest_id, size_t *len);
1386
1387 /* ==================================================================== */
1388 /*
1389 * DES support functions.
1390 */
1391
1392 /*
1393 * Apply DES Initial Permutation.
1394 */
1395 void br_des_do_IP(uint32_t *xl, uint32_t *xr);
1396
1397 /*
1398 * Apply DES Final Permutation (inverse of IP).
1399 */
1400 void br_des_do_invIP(uint32_t *xl, uint32_t *xr);
1401
1402 /*
1403 * Key schedule unit: for a DES key (8 bytes), compute 16 subkeys. Each
1404 * subkey is two 28-bit words represented as two 32-bit words; the PC-2
1405 * bit extration is NOT applied.
1406 */
1407 void br_des_keysched_unit(uint32_t *skey, const void *key);
1408
1409 /*
1410 * Reversal of 16 DES sub-keys (for decryption).
1411 */
1412 void br_des_rev_skey(uint32_t *skey);
1413
1414 /*
1415 * DES/3DES key schedule for 'des_tab' (encryption direction). Returned
1416 * value is the number of rounds.
1417 */
1418 unsigned br_des_tab_keysched(uint32_t *skey, const void *key, size_t key_len);
1419
1420 /*
1421 * DES/3DES key schedule for 'des_ct' (encryption direction). Returned
1422 * value is the number of rounds.
1423 */
1424 unsigned br_des_ct_keysched(uint32_t *skey, const void *key, size_t key_len);
1425
1426 /*
1427 * DES/3DES subkey decompression (from the compressed bitsliced subkeys).
1428 */
1429 void br_des_ct_skey_expand(uint32_t *sk_exp,
1430 unsigned num_rounds, const uint32_t *skey);
1431
1432 /*
1433 * DES/3DES block encryption/decryption ('des_tab').
1434 */
1435 void br_des_tab_process_block(unsigned num_rounds,
1436 const uint32_t *skey, void *block);
1437
1438 /*
1439 * DES/3DES block encryption/decryption ('des_ct').
1440 */
1441 void br_des_ct_process_block(unsigned num_rounds,
1442 const uint32_t *skey, void *block);
1443
1444 /* ==================================================================== */
1445 /*
1446 * AES support functions.
1447 */
1448
1449 /*
1450 * The AES S-box (256-byte table).
1451 */
1452 extern const unsigned char br_aes_S[];
1453
1454 /*
1455 * AES key schedule. skey[] is filled with n+1 128-bit subkeys, where n
1456 * is the number of rounds (10 to 14, depending on key size). The number
1457 * of rounds is returned. If the key size is invalid (not 16, 24 or 32),
1458 * then 0 is returned.
1459 *
1460 * This implementation uses a 256-byte table and is NOT constant-time.
1461 */
1462 unsigned br_aes_keysched(uint32_t *skey, const void *key, size_t key_len);
1463
1464 /*
1465 * AES key schedule for decryption ('aes_big' implementation).
1466 */
1467 unsigned br_aes_big_keysched_inv(uint32_t *skey,
1468 const void *key, size_t key_len);
1469
1470 /*
1471 * AES block encryption with the 'aes_big' implementation (fast, but
1472 * not constant-time). This function encrypts a single block "in place".
1473 */
1474 void br_aes_big_encrypt(unsigned num_rounds, const uint32_t *skey, void *data);
1475
1476 /*
1477 * AES block decryption with the 'aes_big' implementation (fast, but
1478 * not constant-time). This function decrypts a single block "in place".
1479 */
1480 void br_aes_big_decrypt(unsigned num_rounds, const uint32_t *skey, void *data);
1481
1482 /*
1483 * AES block encryption with the 'aes_small' implementation (small, but
1484 * slow and not constant-time). This function encrypts a single block
1485 * "in place".
1486 */
1487 void br_aes_small_encrypt(unsigned num_rounds,
1488 const uint32_t *skey, void *data);
1489
1490 /*
1491 * AES block decryption with the 'aes_small' implementation (small, but
1492 * slow and not constant-time). This function decrypts a single block
1493 * "in place".
1494 */
1495 void br_aes_small_decrypt(unsigned num_rounds,
1496 const uint32_t *skey, void *data);
1497
1498 /*
1499 * The constant-time implementation is "bitsliced": the 128-bit state is
1500 * split over eight 32-bit words q* in the following way:
1501 *
1502 * -- Input block consists in 16 bytes:
1503 * a00 a10 a20 a30 a01 a11 a21 a31 a02 a12 a22 a32 a03 a13 a23 a33
1504 * In the terminology of FIPS 197, this is a 4x4 matrix which is read
1505 * column by column.
1506 *
1507 * -- Each byte is split into eight bits which are distributed over the
1508 * eight words, at the same rank. Thus, for a byte x at rank k, bit 0
1509 * (least significant) of x will be at rank k in q0 (if that bit is b,
1510 * then it contributes "b << k" to the value of q0), bit 1 of x will be
1511 * at rank k in q1, and so on.
1512 *
1513 * -- Ranks given to bits are in "row order" and are either all even, or
1514 * all odd. Two independent AES states are thus interleaved, one using
1515 * the even ranks, the other the odd ranks. Row order means:
1516 * a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23 a30 a31 a32 a33
1517 *
1518 * Converting input bytes from two AES blocks to bitslice representation
1519 * is done in the following way:
1520 * -- Decode first block into the four words q0 q2 q4 q6, in that order,
1521 * using little-endian convention.
1522 * -- Decode second block into the four words q1 q3 q5 q7, in that order,
1523 * using little-endian convention.
1524 * -- Call br_aes_ct_ortho().
1525 *
1526 * Converting back to bytes is done by using the reverse operations. Note
1527 * that br_aes_ct_ortho() is its own inverse.
1528 */
1529
1530 /*
1531 * Perform bytewise orthogonalization of eight 32-bit words. Bytes
1532 * of q0..q7 are spread over all words: for a byte x that occurs
1533 * at rank i in q[j] (byte x uses bits 8*i to 8*i+7 in q[j]), the bit
1534 * of rank k in x (0 <= k <= 7) goes to q[k] at rank 8*i+j.
1535 *
1536 * This operation is an involution.
1537 */
1538 void br_aes_ct_ortho(uint32_t *q);
1539
1540 /*
1541 * The AES S-box, as a bitsliced constant-time version. The input array
1542 * consists in eight 32-bit words; 32 S-box instances are computed in
1543 * parallel. Bits 0 to 7 of each S-box input (bit 0 is least significant)
1544 * are spread over the words 0 to 7, at the same rank.
1545 */
1546 void br_aes_ct_bitslice_Sbox(uint32_t *q);
1547
1548 /*
1549 * Like br_aes_bitslice_Sbox(), but for the inverse S-box.
1550 */
1551 void br_aes_ct_bitslice_invSbox(uint32_t *q);
1552
1553 /*
1554 * Compute AES encryption on bitsliced data. Since input is stored on
1555 * eight 32-bit words, two block encryptions are actually performed
1556 * in parallel.
1557 */
1558 void br_aes_ct_bitslice_encrypt(unsigned num_rounds,
1559 const uint32_t *skey, uint32_t *q);
1560
1561 /*
1562 * Compute AES decryption on bitsliced data. Since input is stored on
1563 * eight 32-bit words, two block decryptions are actually performed
1564 * in parallel.
1565 */
1566 void br_aes_ct_bitslice_decrypt(unsigned num_rounds,
1567 const uint32_t *skey, uint32_t *q);
1568
1569 /*
1570 * AES key schedule, constant-time version. skey[] is filled with n+1
1571 * 128-bit subkeys, where n is the number of rounds (10 to 14, depending
1572 * on key size). The number of rounds is returned. If the key size is
1573 * invalid (not 16, 24 or 32), then 0 is returned.
1574 */
1575 unsigned br_aes_ct_keysched(uint32_t *comp_skey,
1576 const void *key, size_t key_len);
1577
1578 /*
1579 * Expand AES subkeys as produced by br_aes_ct_keysched(), into
1580 * a larger array suitable for br_aes_ct_bitslice_encrypt() and
1581 * br_aes_ct_bitslice_decrypt().
1582 */
1583 void br_aes_ct_skey_expand(uint32_t *skey,
1584 unsigned num_rounds, const uint32_t *comp_skey);
1585
1586 /*
1587 * For the ct64 implementation, the same bitslicing technique is used,
1588 * but four instances are interleaved. First instance uses bits 0, 4,
1589 * 8, 12,... of each word; second instance uses bits 1, 5, 9, 13,...
1590 * and so on.
1591 */
1592
1593 /*
1594 * Perform bytewise orthogonalization of eight 64-bit words. Bytes
1595 * of q0..q7 are spread over all words: for a byte x that occurs
1596 * at rank i in q[j] (byte x uses bits 8*i to 8*i+7 in q[j]), the bit
1597 * of rank k in x (0 <= k <= 7) goes to q[k] at rank 8*i+j.
1598 *
1599 * This operation is an involution.
1600 */
1601 void br_aes_ct64_ortho(uint64_t *q);
1602
1603 /*
1604 * Interleave bytes for an AES input block. If input bytes are
1605 * denoted 0123456789ABCDEF, and have been decoded with little-endian
1606 * convention (w[0] contains 0123, with '3' being most significant;
1607 * w[1] contains 4567, and so on), then output word q0 will be
1608 * set to 08192A3B (again little-endian convention) and q1 will
1609 * be set to 4C5D6E7F.
1610 */
1611 void br_aes_ct64_interleave_in(uint64_t *q0, uint64_t *q1, const uint32_t *w);
1612
1613 /*
1614 * Perform the opposite of br_aes_ct64_interleave_in().
1615 */
1616 void br_aes_ct64_interleave_out(uint32_t *w, uint64_t q0, uint64_t q1);
1617
1618 /*
1619 * The AES S-box, as a bitsliced constant-time version. The input array
1620 * consists in eight 64-bit words; 64 S-box instances are computed in
1621 * parallel. Bits 0 to 7 of each S-box input (bit 0 is least significant)
1622 * are spread over the words 0 to 7, at the same rank.
1623 */
1624 void br_aes_ct64_bitslice_Sbox(uint64_t *q);
1625
1626 /*
1627 * Like br_aes_bitslice_Sbox(), but for the inverse S-box.
1628 */
1629 void br_aes_ct64_bitslice_invSbox(uint64_t *q);
1630
1631 /*
1632 * Compute AES encryption on bitsliced data. Since input is stored on
1633 * eight 64-bit words, four block encryptions are actually performed
1634 * in parallel.
1635 */
1636 void br_aes_ct64_bitslice_encrypt(unsigned num_rounds,
1637 const uint64_t *skey, uint64_t *q);
1638
1639 /*
1640 * Compute AES decryption on bitsliced data. Since input is stored on
1641 * eight 64-bit words, four block decryptions are actually performed
1642 * in parallel.
1643 */
1644 void br_aes_ct64_bitslice_decrypt(unsigned num_rounds,
1645 const uint64_t *skey, uint64_t *q);
1646
1647 /*
1648 * AES key schedule, constant-time version. skey[] is filled with n+1
1649 * 128-bit subkeys, where n is the number of rounds (10 to 14, depending
1650 * on key size). The number of rounds is returned. If the key size is
1651 * invalid (not 16, 24 or 32), then 0 is returned.
1652 */
1653 unsigned br_aes_ct64_keysched(uint64_t *comp_skey,
1654 const void *key, size_t key_len);
1655
1656 /*
1657 * Expand AES subkeys as produced by br_aes_ct64_keysched(), into
1658 * a larger array suitable for br_aes_ct64_bitslice_encrypt() and
1659 * br_aes_ct64_bitslice_decrypt().
1660 */
1661 void br_aes_ct64_skey_expand(uint64_t *skey,
1662 unsigned num_rounds, const uint64_t *comp_skey);
1663
1664 /*
1665 * Test support for AES-NI opcodes.
1666 */
1667 int br_aes_x86ni_supported(void);
1668
1669 /*
1670 * AES key schedule, using x86 AES-NI instructions. This yields the
1671 * subkeys in the encryption direction. Number of rounds is returned.
1672 * Key size MUST be 16, 24 or 32 bytes; otherwise, 0 is returned.
1673 */
1674 unsigned br_aes_x86ni_keysched_enc(unsigned char *skni,
1675 const void *key, size_t len);
1676
1677 /*
1678 * AES key schedule, using x86 AES-NI instructions. This yields the
1679 * subkeys in the decryption direction. Number of rounds is returned.
1680 * Key size MUST be 16, 24 or 32 bytes; otherwise, 0 is returned.
1681 */
1682 unsigned br_aes_x86ni_keysched_dec(unsigned char *skni,
1683 const void *key, size_t len);
1684
1685 /*
1686 * Test support for AES POWER8 opcodes.
1687 */
1688 int br_aes_pwr8_supported(void);
1689
1690 /*
1691 * AES key schedule, using POWER8 instructions. This yields the
1692 * subkeys in the encryption direction. Number of rounds is returned.
1693 * Key size MUST be 16, 24 or 32 bytes; otherwise, 0 is returned.
1694 */
1695 unsigned br_aes_pwr8_keysched(unsigned char *skni,
1696 const void *key, size_t len);
1697
1698 /* ==================================================================== */
1699 /*
1700 * RSA.
1701 */
1702
1703 /*
1704 * Apply proper PKCS#1 v1.5 padding (for signatures). 'hash_oid' is
1705 * the encoded hash function OID, or NULL.
1706 */
1707 uint32_t br_rsa_pkcs1_sig_pad(const unsigned char *hash_oid,
1708 const unsigned char *hash, size_t hash_len,
1709 uint32_t n_bitlen, unsigned char *x);
1710
1711 /*
1712 * Check PKCS#1 v1.5 padding (for signatures). 'hash_oid' is the encoded
1713 * hash function OID, or NULL. The provided 'sig' value is _after_ the
1714 * modular exponentiation, i.e. it should be the padded hash. On
1715 * success, the hashed message is extracted.
1716 */
1717 uint32_t br_rsa_pkcs1_sig_unpad(const unsigned char *sig, size_t sig_len,
1718 const unsigned char *hash_oid, size_t hash_len,
1719 unsigned char *hash_out);
1720
1721 /* ==================================================================== */
1722 /*
1723 * Elliptic curves.
1724 */
1725
1726 /*
1727 * Type for generic EC parameters: curve order (unsigned big-endian
1728 * encoding) and encoded conventional generator.
1729 */
1730 typedef struct {
1731 int curve;
1732 const unsigned char *order;
1733 size_t order_len;
1734 const unsigned char *generator;
1735 size_t generator_len;
1736 } br_ec_curve_def;
1737
1738 extern const br_ec_curve_def br_secp256r1;
1739 extern const br_ec_curve_def br_secp384r1;
1740 extern const br_ec_curve_def br_secp521r1;
1741
1742 /*
1743 * For Curve25519, the advertised "order" really is 2^255-1, since the
1744 * point multipliction function really works over arbitrary 255-bit
1745 * scalars. This value is only meant as a hint for ECDH key generation;
1746 * only ECDSA uses the exact curve order, and ECDSA is not used with
1747 * that specific curve.
1748 */
1749 extern const br_ec_curve_def br_curve25519;
1750
1751 /*
1752 * Decode some bytes as an i31 integer, with truncation (corresponding
1753 * to the 'bits2int' operation in RFC 6979). The target ENCODED bit
1754 * length is provided as last parameter. The resulting value will have
1755 * this declared bit length, and consists the big-endian unsigned decoding
1756 * of exactly that many bits in the source (capped at the source length).
1757 */
1758 void br_ecdsa_i31_bits2int(uint32_t *x,
1759 const void *src, size_t len, uint32_t ebitlen);
1760
1761 /*
1762 * Decode some bytes as an i15 integer, with truncation (corresponding
1763 * to the 'bits2int' operation in RFC 6979). The target ENCODED bit
1764 * length is provided as last parameter. The resulting value will have
1765 * this declared bit length, and consists the big-endian unsigned decoding
1766 * of exactly that many bits in the source (capped at the source length).
1767 */
1768 void br_ecdsa_i15_bits2int(uint16_t *x,
1769 const void *src, size_t len, uint32_t ebitlen);
1770
1771 /* ==================================================================== */
1772 /*
1773 * SSL/TLS support functions.
1774 */
1775
1776 /*
1777 * Record types.
1778 */
1779 #define BR_SSL_CHANGE_CIPHER_SPEC 20
1780 #define BR_SSL_ALERT 21
1781 #define BR_SSL_HANDSHAKE 22
1782 #define BR_SSL_APPLICATION_DATA 23
1783
1784 /*
1785 * Handshake message types.
1786 */
1787 #define BR_SSL_HELLO_REQUEST 0
1788 #define BR_SSL_CLIENT_HELLO 1
1789 #define BR_SSL_SERVER_HELLO 2
1790 #define BR_SSL_CERTIFICATE 11
1791 #define BR_SSL_SERVER_KEY_EXCHANGE 12
1792 #define BR_SSL_CERTIFICATE_REQUEST 13
1793 #define BR_SSL_SERVER_HELLO_DONE 14
1794 #define BR_SSL_CERTIFICATE_VERIFY 15
1795 #define BR_SSL_CLIENT_KEY_EXCHANGE 16
1796 #define BR_SSL_FINISHED 20
1797
1798 /*
1799 * Alert levels.
1800 */
1801 #define BR_LEVEL_WARNING 1
1802 #define BR_LEVEL_FATAL 2
1803
1804 /*
1805 * Low-level I/O state.
1806 */
1807 #define BR_IO_FAILED 0
1808 #define BR_IO_IN 1
1809 #define BR_IO_OUT 2
1810 #define BR_IO_INOUT 3
1811
1812 /*
1813 * Mark a SSL engine as failed. The provided error code is recorded if
1814 * the engine was not already marked as failed. If 'err' is 0, then the
1815 * engine is marked as closed (without error).
1816 */
1817 void br_ssl_engine_fail(br_ssl_engine_context *cc, int err);
1818
1819 /*
1820 * Test whether the engine is closed (normally or as a failure).
1821 */
1822 static inline int
1823 br_ssl_engine_closed(const br_ssl_engine_context *cc)
1824 {
1825 return cc->iomode == BR_IO_FAILED;
1826 }
1827
1828 /*
1829 * Configure a new maximum fragment length. If possible, the maximum
1830 * length for outgoing records is immediately adjusted (if there are
1831 * not already too many buffered bytes for that).
1832 */
1833 void br_ssl_engine_new_max_frag_len(
1834 br_ssl_engine_context *rc, unsigned max_frag_len);
1835
1836 /*
1837 * Test whether the current incoming record has been fully received
1838 * or not. This functions returns 0 only if a complete record header
1839 * has been received, but some of the (possibly encrypted) payload
1840 * has not yet been obtained.
1841 */
1842 int br_ssl_engine_recvrec_finished(const br_ssl_engine_context *rc);
1843
1844 /*
1845 * Flush the current record (if not empty). This is meant to be called
1846 * from the handshake processor only.
1847 */
1848 void br_ssl_engine_flush_record(br_ssl_engine_context *cc);
1849
1850 /*
1851 * Test whether there is some accumulated payload to send.
1852 */
1853 static inline int
1854 br_ssl_engine_has_pld_to_send(const br_ssl_engine_context *rc)
1855 {
1856 return rc->oxa != rc->oxb && rc->oxa != rc->oxc;
1857 }
1858
1859 /*
1860 * Initialize RNG in engine. Returned value is 1 on success, 0 on error.
1861 * This function will try to use the OS-provided RNG, if available. If
1862 * there is no OS-provided RNG, or if it failed, and no entropy was
1863 * injected by the caller, then a failure will be reported. On error,
1864 * the context error code is set.
1865 */
1866 int br_ssl_engine_init_rand(br_ssl_engine_context *cc);
1867
1868 /*
1869 * Reset the handshake-related parts of the engine.
1870 */
1871 void br_ssl_engine_hs_reset(br_ssl_engine_context *cc,
1872 void (*hsinit)(void *), void (*hsrun)(void *));
1873
1874 /*
1875 * Get the PRF to use for this context, for the provided PRF hash
1876 * function ID.
1877 */
1878 br_tls_prf_impl br_ssl_engine_get_PRF(br_ssl_engine_context *cc, int prf_id);
1879
1880 /*
1881 * Consume the provided pre-master secret and compute the corresponding
1882 * master secret. The 'prf_id' is the ID of the hash function to use
1883 * with the TLS 1.2 PRF (ignored if the version is TLS 1.0 or 1.1).
1884 */
1885 void br_ssl_engine_compute_master(br_ssl_engine_context *cc,
1886 int prf_id, const void *pms, size_t len);
1887
1888 /*
1889 * Switch to CBC decryption for incoming records.
1890 * cc the engine context
1891 * is_client non-zero for a client, zero for a server
1892 * prf_id id of hash function for PRF (ignored if not TLS 1.2+)
1893 * mac_id id of hash function for HMAC
1894 * bc_impl block cipher implementation (CBC decryption)
1895 * cipher_key_len block cipher key length (in bytes)
1896 */
1897 void br_ssl_engine_switch_cbc_in(br_ssl_engine_context *cc,
1898 int is_client, int prf_id, int mac_id,
1899 const br_block_cbcdec_class *bc_impl, size_t cipher_key_len);
1900
1901 /*
1902 * Switch to CBC encryption for outgoing records.
1903 * cc the engine context
1904 * is_client non-zero for a client, zero for a server
1905 * prf_id id of hash function for PRF (ignored if not TLS 1.2+)
1906 * mac_id id of hash function for HMAC
1907 * bc_impl block cipher implementation (CBC encryption)
1908 * cipher_key_len block cipher key length (in bytes)
1909 */
1910 void br_ssl_engine_switch_cbc_out(br_ssl_engine_context *cc,
1911 int is_client, int prf_id, int mac_id,
1912 const br_block_cbcenc_class *bc_impl, size_t cipher_key_len);
1913
1914 /*
1915 * Switch to GCM decryption for incoming records.
1916 * cc the engine context
1917 * is_client non-zero for a client, zero for a server
1918 * prf_id id of hash function for PRF
1919 * bc_impl block cipher implementation (CTR)
1920 * cipher_key_len block cipher key length (in bytes)
1921 */
1922 void br_ssl_engine_switch_gcm_in(br_ssl_engine_context *cc,
1923 int is_client, int prf_id,
1924 const br_block_ctr_class *bc_impl, size_t cipher_key_len);
1925
1926 /*
1927 * Switch to GCM encryption for outgoing records.
1928 * cc the engine context
1929 * is_client non-zero for a client, zero for a server
1930 * prf_id id of hash function for PRF
1931 * bc_impl block cipher implementation (CTR)
1932 * cipher_key_len block cipher key length (in bytes)
1933 */
1934 void br_ssl_engine_switch_gcm_out(br_ssl_engine_context *cc,
1935 int is_client, int prf_id,
1936 const br_block_ctr_class *bc_impl, size_t cipher_key_len);
1937
1938 /*
1939 * Switch to ChaCha20+Poly1305 decryption for incoming records.
1940 * cc the engine context
1941 * is_client non-zero for a client, zero for a server
1942 * prf_id id of hash function for PRF
1943 */
1944 void br_ssl_engine_switch_chapol_in(br_ssl_engine_context *cc,
1945 int is_client, int prf_id);
1946
1947 /*
1948 * Switch to ChaCha20+Poly1305 encryption for outgoing records.
1949 * cc the engine context
1950 * is_client non-zero for a client, zero for a server
1951 * prf_id id of hash function for PRF
1952 */
1953 void br_ssl_engine_switch_chapol_out(br_ssl_engine_context *cc,
1954 int is_client, int prf_id);
1955
1956 /*
1957 * Calls to T0-generated code.
1958 */
1959 void br_ssl_hs_client_init_main(void *ctx);
1960 void br_ssl_hs_client_run(void *ctx);
1961 void br_ssl_hs_server_init_main(void *ctx);
1962 void br_ssl_hs_server_run(void *ctx);
1963
1964 /*
1965 * Get the hash function to use for signatures, given a bit mask of
1966 * supported hash functions. This implements a strict choice order
1967 * (namely SHA-256, SHA-384, SHA-512, SHA-224, SHA-1). If the mask
1968 * does not document support of any of these hash functions, then this
1969 * functions returns 0.
1970 */
1971 int br_ssl_choose_hash(unsigned bf);
1972
1973 /* ==================================================================== */
1974
1975 /*
1976 * PowerPC / POWER assembly stuff. The special BR_POWER_ASM_MACROS macro
1977 * must be defined before including this file; this is done by source
1978 * files that use some inline assembly for PowerPC / POWER machines.
1979 */
1980
1981 #if BR_POWER_ASM_MACROS
1982
1983 #define lxvw4x(xt, ra, rb) lxvw4x_(xt, ra, rb)
1984 #define stxvw4x(xt, ra, rb) stxvw4x_(xt, ra, rb)
1985
1986 #define bdnz(foo) bdnz_(foo)
1987 #define beq(foo) beq_(foo)
1988
1989 #define li(rx, value) li_(rx, value)
1990 #define addi(rx, ra, imm) addi_(rx, ra, imm)
1991 #define cmpldi(rx, imm) cmpldi_(rx, imm)
1992 #define mtctr(rx) mtctr_(rx)
1993 #define vspltb(vrt, vrb, uim) vspltb_(vrt, vrb, uim)
1994 #define vspltw(vrt, vrb, uim) vspltw_(vrt, vrb, uim)
1995 #define vspltisb(vrt, imm) vspltisb_(vrt, imm)
1996 #define vspltisw(vrt, imm) vspltisw_(vrt, imm)
1997 #define vrlw(vrt, vra, vrb) vrlw_(vrt, vra, vrb)
1998 #define vsbox(vrt, vra) vsbox_(vrt, vra)
1999 #define vxor(vrt, vra, vrb) vxor_(vrt, vra, vrb)
2000 #define vand(vrt, vra, vrb) vand_(vrt, vra, vrb)
2001 #define vsro(vrt, vra, vrb) vsro_(vrt, vra, vrb)
2002 #define vsl(vrt, vra, vrb) vsl_(vrt, vra, vrb)
2003 #define vsldoi(vt, va, vb, sh) vsldoi_(vt, va, vb, sh)
2004 #define vsr(vrt, vra, vrb) vsr_(vrt, vra, vrb)
2005 #define vadduwm(vrt, vra, vrb) vadduwm_(vrt, vra, vrb)
2006 #define vsububm(vrt, vra, vrb) vsububm_(vrt, vra, vrb)
2007 #define vsubuwm(vrt, vra, vrb) vsubuwm_(vrt, vra, vrb)
2008 #define vsrw(vrt, vra, vrb) vsrw_(vrt, vra, vrb)
2009 #define vcipher(vt, va, vb) vcipher_(vt, va, vb)
2010 #define vcipherlast(vt, va, vb) vcipherlast_(vt, va, vb)
2011 #define vncipher(vt, va, vb) vncipher_(vt, va, vb)
2012 #define vncipherlast(vt, va, vb) vncipherlast_(vt, va, vb)
2013 #define vperm(vt, va, vb, vc) vperm_(vt, va, vb, vc)
2014 #define vpmsumd(vt, va, vb) vpmsumd_(vt, va, vb)
2015 #define xxpermdi(vt, va, vb, d) xxpermdi_(vt, va, vb, d)
2016
2017 #define lxvw4x_(xt, ra, rb) "\tlxvw4x\t" #xt "," #ra "," #rb "\n"
2018 #define stxvw4x_(xt, ra, rb) "\tstxvw4x\t" #xt "," #ra "," #rb "\n"
2019
2020 #define label(foo) #foo "%=:\n"
2021 #define bdnz_(foo) "\tbdnz\t" #foo "%=\n"
2022 #define beq_(foo) "\tbeq\t" #foo "%=\n"
2023
2024 #define li_(rx, value) "\tli\t" #rx "," #value "\n"
2025 #define addi_(rx, ra, imm) "\taddi\t" #rx "," #ra "," #imm "\n"
2026 #define cmpldi_(rx, imm) "\tcmpldi\t" #rx "," #imm "\n"
2027 #define mtctr_(rx) "\tmtctr\t" #rx "\n"
2028 #define vspltb_(vrt, vrb, uim) "\tvspltb\t" #vrt "," #vrb "," #uim "\n"
2029 #define vspltw_(vrt, vrb, uim) "\tvspltw\t" #vrt "," #vrb "," #uim "\n"
2030 #define vspltisb_(vrt, imm) "\tvspltisb\t" #vrt "," #imm "\n"
2031 #define vspltisw_(vrt, imm) "\tvspltisw\t" #vrt "," #imm "\n"
2032 #define vrlw_(vrt, vra, vrb) "\tvrlw\t" #vrt "," #vra "," #vrb "\n"
2033 #define vsbox_(vrt, vra) "\tvsbox\t" #vrt "," #vra "\n"
2034 #define vxor_(vrt, vra, vrb) "\tvxor\t" #vrt "," #vra "," #vrb "\n"
2035 #define vand_(vrt, vra, vrb) "\tvand\t" #vrt "," #vra "," #vrb "\n"
2036 #define vsro_(vrt, vra, vrb) "\tvsro\t" #vrt "," #vra "," #vrb "\n"
2037 #define vsl_(vrt, vra, vrb) "\tvsl\t" #vrt "," #vra "," #vrb "\n"
2038 #define vsldoi_(vt, va, vb, sh) "\tvsldoi\t" #vt "," #va "," #vb "," #sh "\n"
2039 #define vsr_(vrt, vra, vrb) "\tvsr\t" #vrt "," #vra "," #vrb "\n"
2040 #define vadduwm_(vrt, vra, vrb) "\tvadduwm\t" #vrt "," #vra "," #vrb "\n"
2041 #define vsububm_(vrt, vra, vrb) "\tvsububm\t" #vrt "," #vra "," #vrb "\n"
2042 #define vsubuwm_(vrt, vra, vrb) "\tvsubuwm\t" #vrt "," #vra "," #vrb "\n"
2043 #define vsrw_(vrt, vra, vrb) "\tvsrw\t" #vrt "," #vra "," #vrb "\n"
2044 #define vcipher_(vt, va, vb) "\tvcipher\t" #vt "," #va "," #vb "\n"
2045 #define vcipherlast_(vt, va, vb) "\tvcipherlast\t" #vt "," #va "," #vb "\n"
2046 #define vncipher_(vt, va, vb) "\tvncipher\t" #vt "," #va "," #vb "\n"
2047 #define vncipherlast_(vt, va, vb) "\tvncipherlast\t" #vt "," #va "," #vb "\n"
2048 #define vperm_(vt, va, vb, vc) "\tvperm\t" #vt "," #va "," #vb "," #vc "\n"
2049 #define vpmsumd_(vt, va, vb) "\tvpmsumd\t" #vt "," #va "," #vb "\n"
2050 #define xxpermdi_(vt, va, vb, d) "\txxpermdi\t" #vt "," #va "," #vb "," #d "\n"
2051
2052 #endif
2053
2054 /* ==================================================================== */
2055
2056 #endif