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