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