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