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