xref: /freebsd/contrib/bearssl/src/ssl/ssl_engine.c (revision 8aac90f18aef7c9eea906c3ff9a001ca7b94f375)
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 #include "inner.h"
26 
27 #if 0
28 /* obsolete */
29 
30 /*
31  * If BR_USE_URANDOM is not defined, then try to autodetect its presence
32  * through compiler macros.
33  */
34 #ifndef BR_USE_URANDOM
35 
36 /*
37  * Macro values documented on:
38  *    https://sourceforge.net/p/predef/wiki/OperatingSystems/
39  *
40  * Only the most common systems have been included here for now. This
41  * should be enriched later on.
42  */
43 #if defined _AIX \
44 	|| defined __ANDROID__ \
45 	|| defined __FreeBSD__ \
46 	|| defined __NetBSD__ \
47 	|| defined __OpenBSD__ \
48 	|| defined __DragonFly__ \
49 	|| defined __linux__ \
50 	|| (defined __sun && (defined __SVR4 || defined __svr4__)) \
51 	|| (defined __APPLE__ && defined __MACH__)
52 #define BR_USE_URANDOM   1
53 #endif
54 
55 #endif
56 
57 /*
58  * If BR_USE_WIN32_RAND is not defined, perform autodetection here.
59  */
60 #ifndef BR_USE_WIN32_RAND
61 
62 #if defined _WIN32 || defined _WIN64
63 #define BR_USE_WIN32_RAND   1
64 #endif
65 
66 #endif
67 
68 #if BR_USE_URANDOM
69 #include <sys/types.h>
70 #include <unistd.h>
71 #include <fcntl.h>
72 #include <errno.h>
73 #endif
74 
75 #if BR_USE_WIN32_RAND
76 #include <windows.h>
77 #include <wincrypt.h>
78 #pragma comment(lib, "advapi32")
79 #endif
80 
81 #endif
82 
83 /* ==================================================================== */
84 /*
85  * This part of the file does the low-level record management.
86  */
87 
88 /*
89  * IMPLEMENTATION NOTES
90  * ====================
91  *
92  * In this file, we designate by "input" (and the "i" letter) the "recv"
93  * operations: incoming records from the peer, from which payload data
94  * is obtained, and must be extracted by the application (or the SSL
95  * handshake engine). Similarly, "output" (and the "o" letter) is for
96  * "send": payload data injected by the application (and SSL handshake
97  * engine), to be wrapped into records, that are then conveyed to the
98  * peer over the transport medium.
99  *
100  * The input and output buffers may be distinct or shared. When
101  * shared, input and output cannot occur concurrently; the caller
102  * must make sure that it never needs to output data while input
103  * data has been received. In practice, a shared buffer prevents
104  * pipelining of HTTP requests, or similar protocols; however, a
105  * shared buffer saves RAM.
106  *
107  * The input buffer is pointed to by 'ibuf' and has size 'ibuf_len';
108  * the output buffer is pointed to by 'obuf' and has size 'obuf_len'.
109  * From the size of these buffers is derived the maximum fragment
110  * length, which will be honoured upon sending records; regardless of
111  * that length, incoming records will be processed as long as they
112  * fit in the input buffer, and their length still complies with the
113  * protocol specification (maximum plaintext payload length is 16384
114  * bytes).
115  *
116  * Three registers are used to manage buffering in ibuf, called ixa,
117  * ixb and ixc. Similarly, three registers are used to manage buffering
118  * in obuf, called oxa, oxb and oxc.
119  *
120  *
121  * At any time, the engine is in one of the following modes:
122  * -- Failed mode: an error occurs, no I/O can happen.
123  * -- Input mode: the engine can either receive record bytes from the
124  * transport layer, or it has some buffered payload bytes to yield.
125  * -- Output mode: the engine can either receive payload bytes, or it
126  * has some record bytes to send to the transport layer.
127  * -- Input/Output mode: both input and output modes are active. When
128  * the buffer is shared, this can happen only when the buffer is empty
129  * (no buffered payload bytes or record bytes in either direction).
130  *
131  *
132  * Failed mode:
133  * ------------
134  *
135  * I/O failed for some reason (invalid received data, not enough room
136  * for the next record...). No I/O may ever occur again for this context,
137  * until an explicit reset is performed. This mode, and the error code,
138  * are also used for protocol errors, especially handshake errors.
139  *
140  *
141  * Input mode:
142  * -----------
143  *
144  *  ixa   index within ibuf[] for the currently read data
145  *  ixb   maximum index within ibuf[] for the currently read data
146  *  ixc   number of bytes not yet received for the current record
147  *
148  * -- When ixa == ixb, there is no available data for readers. When
149  * ixa != ixb, there is available data and it starts at offset ixa.
150  *
151  * -- When waiting for the next record header, ixa and ixb are equal
152  * and contain a value ranging from 0 to 4; ixc is equal to 5-ixa.
153  *
154  * -- When the header has been received, record data is obtained. The
155  * ixc field records how many bytes are still needed to reach the
156  * end of the current record.
157  *
158  *    ** If encryption is active, then ixa and ixb are kept equal, and
159  *    point to the end of the currently received record bytes. When
160  *    ixc reaches 0, decryption/MAC is applied, and ixa and ixb are
161  *    adjusted.
162  *
163  *    ** If encryption is not active, then ixa and ixb are distinct
164  *    and data can be read right away. Additional record data is
165  *    obtained only when ixa == ixb.
166  *
167  * Note: in input mode and no encryption, records larger than the buffer
168  * size are allowed. When encryption is active, the complete record must
169  * fit within the buffer, since it cannot be decrypted/MACed until it
170  * has been completely received.
171  *
172  * -- When receiving the next record header, 'version_in' contains the
173  * expected input version (0 if not expecting a specific version); on
174  * mismatch, the mode switches to 'failed'.
175  *
176  * -- When the header has been received, 'version_in' contains the received
177  * version. It is up to the caller to check and adjust the 'version_in' field
178  * to implement the required semantics.
179  *
180  * -- The 'record_type_in' field is updated with the incoming record type
181  * when the next record header has been received.
182  *
183  *
184  * Output mode:
185  * ------------
186  *
187  *  oxa   index within obuf[] for the currently accumulated data
188  *  oxb   maximum index within obuf[] for record data
189  *  oxc   pointer for start of record data, and for record sending
190  *
191  * -- When oxa != oxb, more data can be accumulated into the current
192  * record; when oxa == oxb, a closed record is being sent.
193  *
194  * -- When accumulating data, oxc points to the start of the data.
195  *
196  * -- During record sending, oxa (and oxb) point to the next record byte
197  * to send, and oxc indicates the end of the current record.
198  *
199  * Note: sent records must fit within the buffer, since the header is
200  * adjusted only when the complete record has been assembled.
201  *
202  * -- The 'version_out' and 'record_type_out' fields are used to build the
203  * record header when the mode is switched to 'sending'.
204  *
205  *
206  * Modes:
207  * ------
208  *
209  * The state register iomode contains one of the following values:
210  *
211  *  BR_IO_FAILED   I/O failed
212  *  BR_IO_IN       input mode
213  *  BR_IO_OUT      output mode
214  *  BR_IO_INOUT    input/output mode
215  *
216  * Whether encryption is active on incoming records is indicated by the
217  * incrypt flag. For outgoing records, there is no such flag; "encryption"
218  * is always considered active, but initially uses functions that do not
219  * encrypt anything. The 'incrypt' flag is needed because when there is
220  * no active encryption, records larger than the I/O buffer are accepted.
221  *
222  * Note: we do not support no-encryption modes (MAC only).
223  *
224  * TODO: implement GCM support
225  *
226  *
227  * Misc:
228  * -----
229  *
230  * 'max_frag_len' is the maximum plaintext size for an outgoing record.
231  * By default, it is set to the maximum value that fits in the provided
232  * buffers, in the following list: 512, 1024, 2048, 4096, 16384. The
233  * caller may change it if needed, but the new value MUST still fit in
234  * the buffers, and it MUST be one of the list above for compatibility
235  * with the Maximum Fragment Length extension.
236  *
237  * For incoming records, only the total buffer length and current
238  * encryption mode impact the maximum length for incoming records. The
239  * 'max_frag_len' value is still adjusted so that records up to that
240  * length can be both received and sent.
241  *
242  *
243  * Offsets and lengths:
244  * --------------------
245  *
246  * When sending fragments with TLS-1.1+, the maximum overhead is:
247  *   5 bytes for the record header
248  *   16 bytes for the explicit IV
249  *   48 bytes for the MAC (HMAC/SHA-384)
250  *   16 bytes for the padding (AES)
251  * so a total of 85 extra bytes. Note that we support block cipher sizes
252  * up to 16 bytes (AES) and HMAC output sizes up to 48 bytes (SHA-384).
253  *
254  * With TLS-1.0 and CBC mode, we apply a 1/n-1 split, for a maximum
255  * overhead of:
256  *   5 bytes for the first record header
257  *   32 bytes for the first record payload (AES-CBC + HMAC/SHA-1)
258  *   5 bytes for the second record header
259  *   20 bytes for the MAC (HMAC/SHA-1)
260  *   16 bytes for the padding (AES)
261  *   -1 byte to account for the payload byte in the first record
262  * so a total of 77 extra bytes at most, less than the 85 bytes above.
263  * Note that with TLS-1.0, the MAC is HMAC with either MD5 or SHA-1, but
264  * no other hash function.
265  *
266  * The implementation does not try to send larger records when the current
267  * encryption mode has less overhead.
268  *
269  * Maximum input record overhead is:
270  *   5 bytes for the record header
271  *   16 bytes for the explicit IV (TLS-1.1+)
272  *   48 bytes for the MAC (HMAC/SHA-384)
273  *   256 bytes for the padding
274  * so a total of 325 extra bytes.
275  *
276  * When receiving the next record header, it is written into the buffer
277  * bytes 0 to 4 (inclusive). Record data is always written into buf[]
278  * starting at offset 5. When encryption is active, the plaintext data
279  * may start at a larger offset (e.g. because of an explicit IV).
280  */
281 
282 #define MAX_OUT_OVERHEAD    85
283 #define MAX_IN_OVERHEAD    325
284 
285 /* see inner.h */
286 void
287 br_ssl_engine_fail(br_ssl_engine_context *rc, int err)
288 {
289 	if (rc->iomode != BR_IO_FAILED) {
290 		rc->iomode = BR_IO_FAILED;
291 		rc->err = err;
292 	}
293 }
294 
295 /*
296  * Adjust registers for a new incoming record.
297  */
298 static void
299 make_ready_in(br_ssl_engine_context *rc)
300 {
301 	rc->ixa = rc->ixb = 0;
302 	rc->ixc = 5;
303 	if (rc->iomode == BR_IO_IN) {
304 		rc->iomode = BR_IO_INOUT;
305 	}
306 }
307 
308 /*
309  * Adjust registers for a new outgoing record.
310  */
311 static void
312 make_ready_out(br_ssl_engine_context *rc)
313 {
314 	size_t a, b;
315 
316 	a = 5;
317 	b = rc->obuf_len - a;
318 	rc->out.vtable->max_plaintext(&rc->out.vtable, &a, &b);
319 	if ((b - a) > rc->max_frag_len) {
320 		b = a + rc->max_frag_len;
321 	}
322 	rc->oxa = a;
323 	rc->oxb = b;
324 	rc->oxc = a;
325 	if (rc->iomode == BR_IO_OUT) {
326 		rc->iomode = BR_IO_INOUT;
327 	}
328 }
329 
330 /* see inner.h */
331 void
332 br_ssl_engine_new_max_frag_len(br_ssl_engine_context *rc, unsigned max_frag_len)
333 {
334 	size_t nxb;
335 
336 	rc->max_frag_len = max_frag_len;
337 	nxb = rc->oxc + max_frag_len;
338 	if (rc->oxa < rc->oxb && rc->oxb > nxb && rc->oxa < nxb) {
339 		rc->oxb = nxb;
340 	}
341 }
342 
343 /* see bearssl_ssl.h */
344 void
345 br_ssl_engine_set_buffer(br_ssl_engine_context *rc,
346 	void *buf, size_t buf_len, int bidi)
347 {
348 	if (buf == NULL) {
349 		br_ssl_engine_set_buffers_bidi(rc, NULL, 0, NULL, 0);
350 	} else {
351 		/*
352 		 * In bidirectional mode, we want to maximise input
353 		 * buffer size, since we support arbitrary fragmentation
354 		 * when sending, but the peer will not necessarily
355 		 * comply to any low fragment length (in particular if
356 		 * we are the server, because the maximum fragment
357 		 * length extension is under client control).
358 		 *
359 		 * We keep a minimum size of 512 bytes for the plaintext
360 		 * of our outgoing records.
361 		 *
362 		 * br_ssl_engine_set_buffers_bidi() will compute the maximum
363 		 * fragment length for outgoing records by using the minimum
364 		 * of allocated spaces for both input and output records,
365 		 * rounded down to a standard length.
366 		 */
367 		if (bidi) {
368 			size_t w;
369 
370 			if (buf_len < (512 + MAX_IN_OVERHEAD
371 				+ 512 + MAX_OUT_OVERHEAD))
372 			{
373 				rc->iomode = BR_IO_FAILED;
374 				rc->err = BR_ERR_BAD_PARAM;
375 				return;
376 			} else if (buf_len < (16384 + MAX_IN_OVERHEAD
377 				+ 512 + MAX_OUT_OVERHEAD))
378 			{
379 				w = 512 + MAX_OUT_OVERHEAD;
380 			} else {
381 				w = buf_len - (16384 + MAX_IN_OVERHEAD);
382 			}
383 			br_ssl_engine_set_buffers_bidi(rc,
384 				buf, buf_len - w,
385 				(unsigned char *)buf + w, w);
386 		} else {
387 			br_ssl_engine_set_buffers_bidi(rc,
388 				buf, buf_len, NULL, 0);
389 		}
390 	}
391 }
392 
393 /* see bearssl_ssl.h */
394 void
395 br_ssl_engine_set_buffers_bidi(br_ssl_engine_context *rc,
396 	void *ibuf, size_t ibuf_len, void *obuf, size_t obuf_len)
397 {
398 	rc->iomode = BR_IO_INOUT;
399 	rc->incrypt = 0;
400 	rc->err = BR_ERR_OK;
401 	rc->version_in = 0;
402 	rc->record_type_in = 0;
403 	rc->version_out = 0;
404 	rc->record_type_out = 0;
405 	if (ibuf == NULL) {
406 		if (rc->ibuf == NULL) {
407 			br_ssl_engine_fail(rc, BR_ERR_BAD_PARAM);
408 		}
409 	} else {
410 		unsigned u;
411 
412 		rc->ibuf = ibuf;
413 		rc->ibuf_len = ibuf_len;
414 		if (obuf == NULL) {
415 			obuf = ibuf;
416 			obuf_len = ibuf_len;
417 		}
418 		rc->obuf = obuf;
419 		rc->obuf_len = obuf_len;
420 
421 		/*
422 		 * Compute the maximum fragment length, that fits for
423 		 * both incoming and outgoing records. This length will
424 		 * be used in fragment length negotiation, so we must
425 		 * honour it both ways. Regardless, larger incoming
426 		 * records will be accepted, as long as they fit in the
427 		 * actual buffer size.
428 		 */
429 		for (u = 14; u >= 9; u --) {
430 			size_t flen;
431 
432 			flen = (size_t)1 << u;
433 			if (obuf_len >= flen + MAX_OUT_OVERHEAD
434 				&& ibuf_len >= flen + MAX_IN_OVERHEAD)
435 			{
436 				break;
437 			}
438 		}
439 		if (u == 8) {
440 			br_ssl_engine_fail(rc, BR_ERR_BAD_PARAM);
441 			return;
442 		} else if (u == 13) {
443 			u = 12;
444 		}
445 		rc->max_frag_len = (size_t)1 << u;
446 		rc->log_max_frag_len = u;
447 		rc->peer_log_max_frag_len = 0;
448 	}
449 	rc->out.vtable = &br_sslrec_out_clear_vtable;
450 	make_ready_in(rc);
451 	make_ready_out(rc);
452 }
453 
454 /*
455  * Clear buffers in both directions.
456  */
457 static void
458 engine_clearbuf(br_ssl_engine_context *rc)
459 {
460 	make_ready_in(rc);
461 	make_ready_out(rc);
462 }
463 
464 /*
465  * Make sure the internal PRNG is initialised (but not necessarily
466  * seeded properly yet).
467  */
468 static int
469 rng_init(br_ssl_engine_context *cc)
470 {
471 	const br_hash_class *h;
472 
473 	if (cc->rng_init_done != 0) {
474 		return 1;
475 	}
476 
477 	/*
478 	 * If using TLS-1.2, then SHA-256 or SHA-384 must be present (or
479 	 * both); we prefer SHA-256 which is faster for 32-bit systems.
480 	 *
481 	 * If using TLS-1.0 or 1.1 then SHA-1 must be present.
482 	 *
483 	 * Though HMAC_DRBG/SHA-1 is, as far as we know, as safe as
484 	 * these things can be, we still prefer the SHA-2 functions over
485 	 * SHA-1, if only for public relations (known theoretical
486 	 * weaknesses of SHA-1 with regards to collisions are mostly
487 	 * irrelevant here, but they still make people nervous).
488 	 */
489 	h = br_multihash_getimpl(&cc->mhash, br_sha256_ID);
490 	if (!h) {
491 		h = br_multihash_getimpl(&cc->mhash, br_sha384_ID);
492 		if (!h) {
493 			h = br_multihash_getimpl(&cc->mhash,
494 				br_sha1_ID);
495 			if (!h) {
496 				br_ssl_engine_fail(cc, BR_ERR_BAD_STATE);
497 				return 0;
498 			}
499 		}
500 	}
501 	br_hmac_drbg_init(&cc->rng, h, NULL, 0);
502 	cc->rng_init_done = 1;
503 	return 1;
504 }
505 
506 /* see inner.h */
507 int
508 br_ssl_engine_init_rand(br_ssl_engine_context *cc)
509 {
510 	if (!rng_init(cc)) {
511 		return 0;
512 	}
513 
514 	/*
515 	 * We always try OS/hardware seeding once. If it works, then
516 	 * we assume proper seeding. If not, then external entropy must
517 	 * have been injected; otherwise, we report an error.
518 	 */
519 	if (!cc->rng_os_rand_done) {
520 		br_prng_seeder sd;
521 
522 		sd = br_prng_seeder_system(NULL);
523 		if (sd != 0 && sd(&cc->rng.vtable)) {
524 			cc->rng_init_done = 2;
525 		}
526 		cc->rng_os_rand_done = 1;
527 	}
528 	if (cc->rng_init_done < 2) {
529 		br_ssl_engine_fail(cc, BR_ERR_NO_RANDOM);
530 		return 0;
531 	}
532 	return 1;
533 }
534 
535 /* see bearssl_ssl.h */
536 void
537 br_ssl_engine_inject_entropy(br_ssl_engine_context *cc,
538 	const void *data, size_t len)
539 {
540 	/*
541 	 * Externally provided entropy is assumed to be "good enough"
542 	 * (we cannot really test its quality) so if the RNG structure
543 	 * could be initialised at all, then we marked the RNG as
544 	 * "properly seeded".
545 	 */
546 	if (!rng_init(cc)) {
547 		return;
548 	}
549 	br_hmac_drbg_update(&cc->rng, data, len);
550 	cc->rng_init_done = 2;
551 }
552 
553 /*
554  * We define a few internal functions that implement the low-level engine
555  * API for I/O; the external API (br_ssl_engine_sendapp_buf() and similar
556  * functions) is built upon these function, with special processing for
557  * records which are not of type "application data".
558  *
559  *   recvrec_buf, recvrec_ack     receives bytes from transport medium
560  *   sendrec_buf, sendrec_ack     send bytes to transport medium
561  *   recvpld_buf, recvpld_ack     receives payload data from engine
562  *   sendpld_buf, sendpld_ack     send payload data to engine
563  */
564 
565 static unsigned char *
566 recvrec_buf(const br_ssl_engine_context *rc, size_t *len)
567 {
568 	if (rc->shutdown_recv) {
569 		*len = 0;
570 		return NULL;
571 	}
572 
573 	/*
574 	 * Bytes from the transport can be injected only if the mode is
575 	 * compatible (in or in/out), and ixa == ixb; ixc then contains
576 	 * the number of bytes that are still expected (but it may
577 	 * exceed our buffer size).
578 	 *
579 	 * We cannot get "stuck" here (buffer is full, but still more
580 	 * data is expected) because oversized records are detected when
581 	 * their header is processed.
582 	 */
583 	switch (rc->iomode) {
584 	case BR_IO_IN:
585 	case BR_IO_INOUT:
586 		if (rc->ixa == rc->ixb) {
587 			size_t z;
588 
589 			z = rc->ixc;
590 			if (z > rc->ibuf_len - rc->ixa) {
591 				z = rc->ibuf_len - rc->ixa;
592 			}
593 			*len = z;
594 			return rc->ibuf + rc->ixa;
595 		}
596 		break;
597 	}
598 	*len = 0;
599 	return NULL;
600 }
601 
602 static void
603 recvrec_ack(br_ssl_engine_context *rc, size_t len)
604 {
605 	unsigned char *pbuf;
606 	size_t pbuf_len;
607 
608 	/*
609 	 * Adjust state if necessary (for a shared input/output buffer):
610 	 * we got some incoming bytes, so we cannot (temporarily) handle
611 	 * outgoing data.
612 	 */
613 	if (rc->iomode == BR_IO_INOUT && rc->ibuf == rc->obuf) {
614 		rc->iomode = BR_IO_IN;
615 	}
616 
617 	/*
618 	 * Adjust data pointers.
619 	 */
620 	rc->ixb = (rc->ixa += len);
621 	rc->ixc -= len;
622 
623 	/*
624 	 * If we are receiving a header and did not fully obtained it
625 	 * yet, then just wait for the next bytes.
626 	 */
627 	if (rc->ixa < 5) {
628 		return;
629 	}
630 
631 	/*
632 	 * If we just obtained a full header, process it.
633 	 */
634 	if (rc->ixa == 5) {
635 		unsigned version;
636 		unsigned rlen;
637 
638 		/*
639 		 * Get record type and version. We support only versions
640 		 * 3.x (if the version major number does not match, then
641 		 * we suppose that the record format is too alien for us
642 		 * to process it).
643 		 *
644 		 * Note: right now, we reject clients that try to send
645 		 * a ClientHello in a format compatible with SSL-2.0. It
646 		 * is unclear whether this will ever be supported; and
647 		 * if we want to support it, then this might be done in
648 		 * in the server-specific code, not here.
649 		 */
650 		rc->record_type_in = rc->ibuf[0];
651 		version = br_dec16be(rc->ibuf + 1);
652 		if ((version >> 8) != 3) {
653 			br_ssl_engine_fail(rc, BR_ERR_UNSUPPORTED_VERSION);
654 			return;
655 		}
656 
657 		/*
658 		 * We ensure that successive records have the same
659 		 * version. The handshake code must check and adjust the
660 		 * variables when necessary to accommodate the protocol
661 		 * negotiation details.
662 		 */
663 		if (rc->version_in != 0 && rc->version_in != version) {
664 			br_ssl_engine_fail(rc, BR_ERR_BAD_VERSION);
665 			return;
666 		}
667 		rc->version_in = version;
668 
669 		/*
670 		 * Decode record length. We must check that the length
671 		 * is valid (relatively to the current encryption mode)
672 		 * and also (if encryption is active) that the record
673 		 * will fit in our buffer.
674 		 *
675 		 * When no encryption is active, we can process records
676 		 * by chunks, and thus accept any record up to the
677 		 * maximum allowed plaintext length (16384 bytes).
678 		 */
679 		rlen = br_dec16be(rc->ibuf + 3);
680 		if (rc->incrypt) {
681 			if (!rc->in.vtable->check_length(
682 				&rc->in.vtable, rlen))
683 			{
684 				br_ssl_engine_fail(rc, BR_ERR_BAD_LENGTH);
685 				return;
686 			}
687 			if (rlen > (rc->ibuf_len - 5)) {
688 				br_ssl_engine_fail(rc, BR_ERR_TOO_LARGE);
689 				return;
690 			}
691 		} else {
692 			if (rlen > 16384) {
693 				br_ssl_engine_fail(rc, BR_ERR_BAD_LENGTH);
694 				return;
695 			}
696 		}
697 
698 		/*
699 		 * If the record is completely empty then we must switch
700 		 * to a new record. Note that, in that case, we
701 		 * completely ignore the record type, which is fitting
702 		 * since we received no actual data of that type.
703 		 *
704 		 * A completely empty record is technically allowed as
705 		 * long as encryption/MAC is not active, i.e. before
706 		 * completion of the first handshake. It it still weird;
707 		 * it might conceptually be useful as a heartbeat or
708 		 * keep-alive mechanism while some lengthy operation is
709 		 * going on, e.g. interaction with a human user.
710 		 */
711 		if (rlen == 0) {
712 			make_ready_in(rc);
713 		} else {
714 			rc->ixa = rc->ixb = 5;
715 			rc->ixc = rlen;
716 		}
717 		return;
718 	}
719 
720 	/*
721 	 * If there is no active encryption, then the data can be read
722 	 * right away. Note that we do not receive bytes from the
723 	 * transport medium when we still have payload bytes to be
724 	 * acknowledged.
725 	 */
726 	if (!rc->incrypt) {
727 		rc->ixa = 5;
728 		return;
729 	}
730 
731 	/*
732 	 * Since encryption is active, we must wait for a full record
733 	 * before processing it.
734 	 */
735 	if (rc->ixc != 0) {
736 		return;
737 	}
738 
739 	/*
740 	 * We got the full record. Decrypt it.
741 	 */
742 	pbuf_len = rc->ixa - 5;
743 	pbuf = rc->in.vtable->decrypt(&rc->in.vtable,
744 		rc->record_type_in, rc->version_in, rc->ibuf + 5, &pbuf_len);
745 	if (pbuf == 0) {
746 		br_ssl_engine_fail(rc, BR_ERR_BAD_MAC);
747 		return;
748 	}
749 	rc->ixa = (size_t)(pbuf - rc->ibuf);
750 	rc->ixb = rc->ixa + pbuf_len;
751 
752 	/*
753 	 * Decryption may have yielded an empty record, in which case
754 	 * we get back to "ready" state immediately.
755 	 */
756 	if (rc->ixa == rc->ixb) {
757 		make_ready_in(rc);
758 	}
759 }
760 
761 /* see inner.h */
762 int
763 br_ssl_engine_recvrec_finished(const br_ssl_engine_context *rc)
764 {
765 	switch (rc->iomode) {
766 	case BR_IO_IN:
767 	case BR_IO_INOUT:
768 		return rc->ixc == 0 || rc->ixa < 5;
769 	default:
770 		return 1;
771 	}
772 }
773 
774 static unsigned char *
775 recvpld_buf(const br_ssl_engine_context *rc, size_t *len)
776 {
777 	/*
778 	 * There is payload data to be read only if the mode is
779 	 * compatible, and ixa != ixb.
780 	 */
781 	switch (rc->iomode) {
782 	case BR_IO_IN:
783 	case BR_IO_INOUT:
784 		*len = rc->ixb - rc->ixa;
785 		return (*len == 0) ? NULL : (rc->ibuf + rc->ixa);
786 	default:
787 		*len = 0;
788 		return NULL;
789 	}
790 }
791 
792 static void
793 recvpld_ack(br_ssl_engine_context *rc, size_t len)
794 {
795 	rc->ixa += len;
796 
797 	/*
798 	 * If we read all the available data, then we either expect
799 	 * the remainder of the current record (if the current record
800 	 * was not finished; this may happen when encryption is not
801 	 * active), or go to "ready" state.
802 	 */
803 	if (rc->ixa == rc->ixb) {
804 		if (rc->ixc == 0) {
805 			make_ready_in(rc);
806 		} else {
807 			rc->ixa = rc->ixb = 5;
808 		}
809 	}
810 }
811 
812 static unsigned char *
813 sendpld_buf(const br_ssl_engine_context *rc, size_t *len)
814 {
815 	/*
816 	 * Payload data can be injected only if the current mode is
817 	 * compatible, and oxa != oxb.
818 	 */
819 	switch (rc->iomode) {
820 	case BR_IO_OUT:
821 	case BR_IO_INOUT:
822 		*len = rc->oxb - rc->oxa;
823 		return (*len == 0) ? NULL : (rc->obuf + rc->oxa);
824 	default:
825 		*len = 0;
826 		return NULL;
827 	}
828 }
829 
830 /*
831  * If some payload bytes have been accumulated, then wrap them into
832  * an outgoing record. Otherwise, this function does nothing, unless
833  * 'force' is non-zero, in which case an empty record is assembled.
834  *
835  * The caller must take care not to invoke this function if the engine
836  * is not currently ready to receive payload bytes to send.
837  */
838 static void
839 sendpld_flush(br_ssl_engine_context *rc, int force)
840 {
841 	size_t xlen;
842 	unsigned char *buf;
843 
844 	if (rc->oxa == rc->oxb) {
845 		return;
846 	}
847 	xlen = rc->oxa - rc->oxc;
848 	if (xlen == 0 && !force) {
849 		return;
850 	}
851 	buf = rc->out.vtable->encrypt(&rc->out.vtable,
852 		rc->record_type_out, rc->version_out,
853 		rc->obuf + rc->oxc, &xlen);
854 	rc->oxb = rc->oxa = (size_t)(buf - rc->obuf);
855 	rc->oxc = rc->oxa + xlen;
856 }
857 
858 static void
859 sendpld_ack(br_ssl_engine_context *rc, size_t len)
860 {
861 	/*
862 	 * If using a shared buffer, then we may have to modify the
863 	 * current mode.
864 	 */
865 	if (rc->iomode == BR_IO_INOUT && rc->ibuf == rc->obuf) {
866 		rc->iomode = BR_IO_OUT;
867 	}
868 	rc->oxa += len;
869 	if (rc->oxa >= rc->oxb) {
870 		/*
871 		 * Set oxb to one more than oxa so that sendpld_flush()
872 		 * does not mistakingly believe that a record is
873 		 * already prepared and being sent.
874 		 */
875 		rc->oxb = rc->oxa + 1;
876 		sendpld_flush(rc, 0);
877 	}
878 }
879 
880 static unsigned char *
881 sendrec_buf(const br_ssl_engine_context *rc, size_t *len)
882 {
883 	/*
884 	 * When still gathering payload bytes, oxc points to the start
885 	 * of the record data, so oxc <= oxa. However, when a full
886 	 * record has been completed, oxc points to the end of the record,
887 	 * so oxc > oxa.
888 	 */
889 	switch (rc->iomode) {
890 	case BR_IO_OUT:
891 	case BR_IO_INOUT:
892 		if (rc->oxc > rc->oxa) {
893 			*len = rc->oxc - rc->oxa;
894 			return rc->obuf + rc->oxa;
895 		}
896 		break;
897 	}
898 	*len = 0;
899 	return NULL;
900 }
901 
902 static void
903 sendrec_ack(br_ssl_engine_context *rc, size_t len)
904 {
905 	rc->oxb = (rc->oxa += len);
906 	if (rc->oxa == rc->oxc) {
907 		make_ready_out(rc);
908 	}
909 }
910 
911 /*
912  * Test whether there is some buffered outgoing record that still must
913  * sent.
914  */
915 static inline int
916 has_rec_tosend(const br_ssl_engine_context *rc)
917 {
918 	return rc->oxa == rc->oxb && rc->oxa != rc->oxc;
919 }
920 
921 /*
922  * The "no encryption" mode has no overhead. It limits the payload size
923  * to the maximum size allowed by the standard (16384 bytes); the caller
924  * is responsible for possibly enforcing a smaller fragment length.
925  */
926 static void
927 clear_max_plaintext(const br_sslrec_out_clear_context *cc,
928 	size_t *start, size_t *end)
929 {
930 	size_t len;
931 
932 	(void)cc;
933 	len = *end - *start;
934 	if (len > 16384) {
935 		*end = *start + 16384;
936 	}
937 }
938 
939 /*
940  * In "no encryption" mode, encryption is trivial (a no-operation) so
941  * we just have to encode the header.
942  */
943 static unsigned char *
944 clear_encrypt(br_sslrec_out_clear_context *cc,
945 	int record_type, unsigned version, void *data, size_t *data_len)
946 {
947 	unsigned char *buf;
948 
949 	(void)cc;
950 	buf = (unsigned char *)data - 5;
951 	buf[0] = record_type;
952 	br_enc16be(buf + 1, version);
953 	br_enc16be(buf + 3, *data_len);
954 	*data_len += 5;
955 	return buf;
956 }
957 
958 /* see bearssl_ssl.h */
959 const br_sslrec_out_class br_sslrec_out_clear_vtable = {
960 	sizeof(br_sslrec_out_clear_context),
961 	(void (*)(const br_sslrec_out_class *const *, size_t *, size_t *))
962 		&clear_max_plaintext,
963 	(unsigned char *(*)(const br_sslrec_out_class **,
964 		int, unsigned, void *, size_t *))
965 		&clear_encrypt
966 };
967 
968 /* ==================================================================== */
969 /*
970  * In this part of the file, we handle the various record types, and
971  * communications with the handshake processor.
972  */
973 
974 /*
975  * IMPLEMENTATION NOTES
976  * ====================
977  *
978  * The handshake processor is written in T0 and runs as a coroutine.
979  * It receives the contents of all records except application data, and
980  * is responsible for producing the contents of all records except
981  * application data.
982  *
983  * A state flag is maintained, which specifies whether application data
984  * is acceptable or not. When it is set:
985  *
986  * -- Application data can be injected as payload data (provided that
987  *    the output buffer is ready for that).
988  *
989  * -- Incoming application data records are accepted, and yield data
990  *    that the caller may retrieve.
991  *
992  * When the flag is cleared, application data is not accepted from the
993  * application, and incoming application data records trigger an error.
994  *
995  *
996  * Records of type handshake, alert or change-cipher-spec are handled
997  * by the handshake processor. The handshake processor is written in T0
998  * and runs as a coroutine; it gets invoked whenever one of the following
999  * situations is reached:
1000  *
1001  * -- An incoming record has type handshake, alert or change-cipher-spec,
1002  *    and yields data that can be read (zero-length records are thus
1003  *    ignored).
1004  *
1005  * -- An outgoing record has just finished being sent, and the "application
1006  *    data" flag is cleared.
1007  *
1008  * -- The caller wishes to perform a close (call to br_ssl_engine_close()).
1009  *
1010  * -- The caller wishes to perform a renegotiation (call to
1011  *    br_ssl_engine_renegotiate()).
1012  *
1013  * Whenever the handshake processor is entered, access to the payload
1014  * buffers is provided, along with some information about explicit
1015  * closures or renegotiations.
1016  */
1017 
1018 /* see bearssl_ssl.h */
1019 void
1020 br_ssl_engine_set_suites(br_ssl_engine_context *cc,
1021 	const uint16_t *suites, size_t suites_num)
1022 {
1023 	if ((suites_num * sizeof *suites) > sizeof cc->suites_buf) {
1024 		br_ssl_engine_fail(cc, BR_ERR_BAD_PARAM);
1025 		return;
1026 	}
1027 	memcpy(cc->suites_buf, suites, suites_num * sizeof *suites);
1028 	cc->suites_num = suites_num;
1029 }
1030 
1031 /*
1032  * Give control to handshake processor. 'action' is 1 for a close,
1033  * 2 for a renegotiation, or 0 for a jump due to I/O completion.
1034  */
1035 static void
1036 jump_handshake(br_ssl_engine_context *cc, int action)
1037 {
1038 	/*
1039 	 * We use a loop because the handshake processor actions may
1040 	 * allow for more actions; namely, if the processor reads all
1041 	 * input data, then it may allow for output data to be produced,
1042 	 * in case of a shared in/out buffer.
1043 	 */
1044 	for (;;) {
1045 		size_t hlen_in, hlen_out;
1046 
1047 		/*
1048 		 * Get input buffer. We do not want to provide
1049 		 * application data to the handshake processor (we could
1050 		 * get called with an explicit close or renegotiation
1051 		 * while there is application data ready to be read).
1052 		 */
1053 		cc->hbuf_in = recvpld_buf(cc, &hlen_in);
1054 		if (cc->hbuf_in != NULL
1055 			&& cc->record_type_in == BR_SSL_APPLICATION_DATA)
1056 		{
1057 			hlen_in = 0;
1058 		}
1059 
1060 		/*
1061 		 * Get output buffer. The handshake processor never
1062 		 * leaves an unfinished outgoing record, so if there is
1063 		 * buffered output, then it MUST be some application
1064 		 * data, so the processor cannot write to it.
1065 		 */
1066 		cc->saved_hbuf_out = cc->hbuf_out = sendpld_buf(cc, &hlen_out);
1067 		if (cc->hbuf_out != NULL && br_ssl_engine_has_pld_to_send(cc)) {
1068 			hlen_out = 0;
1069 		}
1070 
1071 		/*
1072 		 * Note: hlen_in and hlen_out can be both non-zero only if
1073 		 * the input and output buffers are disjoint. Thus, we can
1074 		 * offer both buffers to the handshake code.
1075 		 */
1076 
1077 		cc->hlen_in = hlen_in;
1078 		cc->hlen_out = hlen_out;
1079 		cc->action = action;
1080 		cc->hsrun(&cc->cpu);
1081 		if (br_ssl_engine_closed(cc)) {
1082 			return;
1083 		}
1084 		if (cc->hbuf_out != cc->saved_hbuf_out) {
1085 			sendpld_ack(cc, cc->hbuf_out - cc->saved_hbuf_out);
1086 		}
1087 		if (hlen_in != cc->hlen_in) {
1088 			recvpld_ack(cc, hlen_in - cc->hlen_in);
1089 			if (cc->hlen_in == 0) {
1090 				/*
1091 				 * We read all data bytes, which may have
1092 				 * released the output buffer in case it
1093 				 * is shared with the input buffer, and
1094 				 * the handshake code might be waiting for
1095 				 * that.
1096 				 */
1097 				action = 0;
1098 				continue;
1099 			}
1100 		}
1101 		break;
1102 	}
1103 }
1104 
1105 /* see inner.h */
1106 void
1107 br_ssl_engine_flush_record(br_ssl_engine_context *cc)
1108 {
1109 	if (cc->hbuf_out != cc->saved_hbuf_out) {
1110 		sendpld_ack(cc, cc->hbuf_out - cc->saved_hbuf_out);
1111 	}
1112 	if (br_ssl_engine_has_pld_to_send(cc)) {
1113 		sendpld_flush(cc, 0);
1114 	}
1115 	cc->saved_hbuf_out = cc->hbuf_out = sendpld_buf(cc, &cc->hlen_out);
1116 }
1117 
1118 /* see bearssl_ssl.h */
1119 unsigned char *
1120 br_ssl_engine_sendapp_buf(const br_ssl_engine_context *cc, size_t *len)
1121 {
1122 	if (!(cc->application_data & 1)) {
1123 		*len = 0;
1124 		return NULL;
1125 	}
1126 	return sendpld_buf(cc, len);
1127 }
1128 
1129 /* see bearssl_ssl.h */
1130 void
1131 br_ssl_engine_sendapp_ack(br_ssl_engine_context *cc, size_t len)
1132 {
1133 	sendpld_ack(cc, len);
1134 }
1135 
1136 /* see bearssl_ssl.h */
1137 unsigned char *
1138 br_ssl_engine_recvapp_buf(const br_ssl_engine_context *cc, size_t *len)
1139 {
1140 	if (!(cc->application_data & 1)
1141 		|| cc->record_type_in != BR_SSL_APPLICATION_DATA)
1142 	{
1143 		*len = 0;
1144 		return NULL;
1145 	}
1146 	return recvpld_buf(cc, len);
1147 }
1148 
1149 /* see bearssl_ssl.h */
1150 void
1151 br_ssl_engine_recvapp_ack(br_ssl_engine_context *cc, size_t len)
1152 {
1153 	recvpld_ack(cc, len);
1154 }
1155 
1156 /* see bearssl_ssl.h */
1157 unsigned char *
1158 br_ssl_engine_sendrec_buf(const br_ssl_engine_context *cc, size_t *len)
1159 {
1160 	return sendrec_buf(cc, len);
1161 }
1162 
1163 /* see bearssl_ssl.h */
1164 void
1165 br_ssl_engine_sendrec_ack(br_ssl_engine_context *cc, size_t len)
1166 {
1167 	sendrec_ack(cc, len);
1168 	if (len != 0 && !has_rec_tosend(cc)
1169 		&& (cc->record_type_out != BR_SSL_APPLICATION_DATA
1170 		|| (cc->application_data & 1) == 0))
1171 	{
1172 		jump_handshake(cc, 0);
1173 	}
1174 }
1175 
1176 /* see bearssl_ssl.h */
1177 unsigned char *
1178 br_ssl_engine_recvrec_buf(const br_ssl_engine_context *cc, size_t *len)
1179 {
1180 	return recvrec_buf(cc, len);
1181 }
1182 
1183 /* see bearssl_ssl.h */
1184 void
1185 br_ssl_engine_recvrec_ack(br_ssl_engine_context *cc, size_t len)
1186 {
1187 	unsigned char *buf;
1188 
1189 	recvrec_ack(cc, len);
1190 	if (br_ssl_engine_closed(cc)) {
1191 		return;
1192 	}
1193 
1194 	/*
1195 	 * We just received some bytes from the peer. This may have
1196 	 * yielded some payload bytes, in which case we must process
1197 	 * them according to the record type.
1198 	 */
1199 	buf = recvpld_buf(cc, &len);
1200 	if (buf != NULL) {
1201 		switch (cc->record_type_in) {
1202 		case BR_SSL_CHANGE_CIPHER_SPEC:
1203 		case BR_SSL_ALERT:
1204 		case BR_SSL_HANDSHAKE:
1205 			jump_handshake(cc, 0);
1206 			break;
1207 		case BR_SSL_APPLICATION_DATA:
1208 			if (cc->application_data == 1) {
1209 				break;
1210 			}
1211 
1212 			/*
1213 			 * If we are currently closing, and waiting for
1214 			 * a close_notify from the peer, then incoming
1215 			 * application data should be discarded.
1216 			 */
1217 			if (cc->application_data == 2) {
1218 				recvpld_ack(cc, len);
1219 				break;
1220 			}
1221 
1222 			/* Fall through */
1223 		default:
1224 			br_ssl_engine_fail(cc, BR_ERR_UNEXPECTED);
1225 			break;
1226 		}
1227 	}
1228 }
1229 
1230 /* see bearssl_ssl.h */
1231 void
1232 br_ssl_engine_close(br_ssl_engine_context *cc)
1233 {
1234 	if (!br_ssl_engine_closed(cc)) {
1235 		/*
1236 		 * If we are not already closed, then we need to
1237 		 * initiate the closure. Once closing, any incoming
1238 		 * application data is discarded; we should also discard
1239 		 * application data which is already there but has not
1240 		 * been acknowledged by the application yet (this mimics
1241 		 * usual semantics on BSD sockets: you cannot read()
1242 		 * once you called close(), even if there was some
1243 		 * unread data already buffered).
1244 		 */
1245 		size_t len;
1246 
1247 		if (br_ssl_engine_recvapp_buf(cc, &len) != NULL && len != 0) {
1248 			br_ssl_engine_recvapp_ack(cc, len);
1249 		}
1250 		jump_handshake(cc, 1);
1251 	}
1252 }
1253 
1254 /* see bearssl_ssl.h */
1255 int
1256 br_ssl_engine_renegotiate(br_ssl_engine_context *cc)
1257 {
1258 	size_t len;
1259 
1260 	if (br_ssl_engine_closed(cc) || cc->reneg == 1
1261 		|| (cc->flags & BR_OPT_NO_RENEGOTIATION) != 0
1262 		|| br_ssl_engine_recvapp_buf(cc, &len) != NULL)
1263 	{
1264 		return 0;
1265 	}
1266 	jump_handshake(cc, 2);
1267 	return 1;
1268 }
1269 
1270 /* see bearssl.h */
1271 unsigned
1272 br_ssl_engine_current_state(const br_ssl_engine_context *cc)
1273 {
1274 	unsigned s;
1275 	size_t len;
1276 
1277 	if (br_ssl_engine_closed(cc)) {
1278 		return BR_SSL_CLOSED;
1279 	}
1280 
1281 	s = 0;
1282 	if (br_ssl_engine_sendrec_buf(cc, &len) != NULL) {
1283 		s |= BR_SSL_SENDREC;
1284 	}
1285 	if (br_ssl_engine_recvrec_buf(cc, &len) != NULL) {
1286 		s |= BR_SSL_RECVREC;
1287 	}
1288 	if (br_ssl_engine_sendapp_buf(cc, &len) != NULL) {
1289 		s |= BR_SSL_SENDAPP;
1290 	}
1291 	if (br_ssl_engine_recvapp_buf(cc, &len) != NULL) {
1292 		s |= BR_SSL_RECVAPP;
1293 	}
1294 	return s;
1295 }
1296 
1297 /* see bearssl_ssl.h */
1298 void
1299 br_ssl_engine_flush(br_ssl_engine_context *cc, int force)
1300 {
1301 	if (!br_ssl_engine_closed(cc) && (cc->application_data & 1) != 0) {
1302 		sendpld_flush(cc, force);
1303 	}
1304 }
1305 
1306 /* see inner.h */
1307 void
1308 br_ssl_engine_hs_reset(br_ssl_engine_context *cc,
1309 	void (*hsinit)(void *), void (*hsrun)(void *))
1310 {
1311 	engine_clearbuf(cc);
1312 	cc->cpu.dp = cc->dp_stack;
1313 	cc->cpu.rp = cc->rp_stack;
1314 	hsinit(&cc->cpu);
1315 	cc->hsrun = hsrun;
1316 	cc->shutdown_recv = 0;
1317 	cc->application_data = 0;
1318 	cc->alert = 0;
1319 	jump_handshake(cc, 0);
1320 }
1321 
1322 /* see inner.h */
1323 br_tls_prf_impl
1324 br_ssl_engine_get_PRF(br_ssl_engine_context *cc, int prf_id)
1325 {
1326 	if (cc->session.version >= BR_TLS12) {
1327 		if (prf_id == br_sha384_ID) {
1328 			return cc->prf_sha384;
1329 		} else {
1330 			return cc->prf_sha256;
1331 		}
1332 	} else {
1333 		return cc->prf10;
1334 	}
1335 }
1336 
1337 /* see inner.h */
1338 void
1339 br_ssl_engine_compute_master(br_ssl_engine_context *cc,
1340 	int prf_id, const void *pms, size_t pms_len)
1341 {
1342 	br_tls_prf_impl iprf;
1343 	br_tls_prf_seed_chunk seed[2] = {
1344 		{ cc->client_random, sizeof cc->client_random },
1345 		{ cc->server_random, sizeof cc->server_random }
1346 	};
1347 
1348 	iprf = br_ssl_engine_get_PRF(cc, prf_id);
1349 	iprf(cc->session.master_secret, sizeof cc->session.master_secret,
1350 		pms, pms_len, "master secret", 2, seed);
1351 }
1352 
1353 /*
1354  * Compute key block.
1355  */
1356 static void
1357 compute_key_block(br_ssl_engine_context *cc, int prf_id,
1358 	size_t half_len, unsigned char *kb)
1359 {
1360 	br_tls_prf_impl iprf;
1361 	br_tls_prf_seed_chunk seed[2] = {
1362 		{ cc->server_random, sizeof cc->server_random },
1363 		{ cc->client_random, sizeof cc->client_random }
1364 	};
1365 
1366 	iprf = br_ssl_engine_get_PRF(cc, prf_id);
1367 	iprf(kb, half_len << 1,
1368 		cc->session.master_secret, sizeof cc->session.master_secret,
1369 		"key expansion", 2, seed);
1370 }
1371 
1372 /* see inner.h */
1373 void
1374 br_ssl_engine_switch_cbc_in(br_ssl_engine_context *cc,
1375 	int is_client, int prf_id, int mac_id,
1376 	const br_block_cbcdec_class *bc_impl, size_t cipher_key_len)
1377 {
1378 	unsigned char kb[192];
1379 	unsigned char *cipher_key, *mac_key, *iv;
1380 	const br_hash_class *imh;
1381 	size_t mac_key_len, mac_out_len, iv_len;
1382 
1383 	imh = br_ssl_engine_get_hash(cc, mac_id);
1384 	mac_out_len = (imh->desc >> BR_HASHDESC_OUT_OFF) & BR_HASHDESC_OUT_MASK;
1385 	mac_key_len = mac_out_len;
1386 
1387 	/*
1388 	 * TLS 1.1+ uses per-record explicit IV, so no IV to generate here.
1389 	 */
1390 	if (cc->session.version >= BR_TLS11) {
1391 		iv_len = 0;
1392 	} else {
1393 		iv_len = bc_impl->block_size;
1394 	}
1395 	compute_key_block(cc, prf_id,
1396 		mac_key_len + cipher_key_len + iv_len, kb);
1397 	if (is_client) {
1398 		mac_key = &kb[mac_key_len];
1399 		cipher_key = &kb[(mac_key_len << 1) + cipher_key_len];
1400 		iv = &kb[((mac_key_len + cipher_key_len) << 1) + iv_len];
1401 	} else {
1402 		mac_key = &kb[0];
1403 		cipher_key = &kb[mac_key_len << 1];
1404 		iv = &kb[(mac_key_len + cipher_key_len) << 1];
1405 	}
1406 	if (iv_len == 0) {
1407 		iv = NULL;
1408 	}
1409 	cc->icbc_in->init(&cc->in.cbc.vtable,
1410 		bc_impl, cipher_key, cipher_key_len,
1411 		imh, mac_key, mac_key_len, mac_out_len, iv);
1412 	cc->incrypt = 1;
1413 }
1414 
1415 /* see inner.h */
1416 void
1417 br_ssl_engine_switch_cbc_out(br_ssl_engine_context *cc,
1418 	int is_client, int prf_id, int mac_id,
1419 	const br_block_cbcenc_class *bc_impl, size_t cipher_key_len)
1420 {
1421 	unsigned char kb[192];
1422 	unsigned char *cipher_key, *mac_key, *iv;
1423 	const br_hash_class *imh;
1424 	size_t mac_key_len, mac_out_len, iv_len;
1425 
1426 	imh = br_ssl_engine_get_hash(cc, mac_id);
1427 	mac_out_len = (imh->desc >> BR_HASHDESC_OUT_OFF) & BR_HASHDESC_OUT_MASK;
1428 	mac_key_len = mac_out_len;
1429 
1430 	/*
1431 	 * TLS 1.1+ uses per-record explicit IV, so no IV to generate here.
1432 	 */
1433 	if (cc->session.version >= BR_TLS11) {
1434 		iv_len = 0;
1435 	} else {
1436 		iv_len = bc_impl->block_size;
1437 	}
1438 	compute_key_block(cc, prf_id,
1439 		mac_key_len + cipher_key_len + iv_len, kb);
1440 	if (is_client) {
1441 		mac_key = &kb[0];
1442 		cipher_key = &kb[mac_key_len << 1];
1443 		iv = &kb[(mac_key_len + cipher_key_len) << 1];
1444 	} else {
1445 		mac_key = &kb[mac_key_len];
1446 		cipher_key = &kb[(mac_key_len << 1) + cipher_key_len];
1447 		iv = &kb[((mac_key_len + cipher_key_len) << 1) + iv_len];
1448 	}
1449 	if (iv_len == 0) {
1450 		iv = NULL;
1451 	}
1452 	cc->icbc_out->init(&cc->out.cbc.vtable,
1453 		bc_impl, cipher_key, cipher_key_len,
1454 		imh, mac_key, mac_key_len, mac_out_len, iv);
1455 }
1456 
1457 /* see inner.h */
1458 void
1459 br_ssl_engine_switch_gcm_in(br_ssl_engine_context *cc,
1460 	int is_client, int prf_id,
1461 	const br_block_ctr_class *bc_impl, size_t cipher_key_len)
1462 {
1463 	unsigned char kb[72];
1464 	unsigned char *cipher_key, *iv;
1465 
1466 	compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1467 	if (is_client) {
1468 		cipher_key = &kb[cipher_key_len];
1469 		iv = &kb[(cipher_key_len << 1) + 4];
1470 	} else {
1471 		cipher_key = &kb[0];
1472 		iv = &kb[cipher_key_len << 1];
1473 	}
1474 	cc->igcm_in->init(&cc->in.gcm.vtable.in,
1475 		bc_impl, cipher_key, cipher_key_len, cc->ighash, iv);
1476 	cc->incrypt = 1;
1477 }
1478 
1479 /* see inner.h */
1480 void
1481 br_ssl_engine_switch_gcm_out(br_ssl_engine_context *cc,
1482 	int is_client, int prf_id,
1483 	const br_block_ctr_class *bc_impl, size_t cipher_key_len)
1484 {
1485 	unsigned char kb[72];
1486 	unsigned char *cipher_key, *iv;
1487 
1488 	compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1489 	if (is_client) {
1490 		cipher_key = &kb[0];
1491 		iv = &kb[cipher_key_len << 1];
1492 	} else {
1493 		cipher_key = &kb[cipher_key_len];
1494 		iv = &kb[(cipher_key_len << 1) + 4];
1495 	}
1496 	cc->igcm_out->init(&cc->out.gcm.vtable.out,
1497 		bc_impl, cipher_key, cipher_key_len, cc->ighash, iv);
1498 }
1499 
1500 /* see inner.h */
1501 void
1502 br_ssl_engine_switch_chapol_in(br_ssl_engine_context *cc,
1503 	int is_client, int prf_id)
1504 {
1505 	unsigned char kb[88];
1506 	unsigned char *cipher_key, *iv;
1507 
1508 	compute_key_block(cc, prf_id, 44, kb);
1509 	if (is_client) {
1510 		cipher_key = &kb[32];
1511 		iv = &kb[76];
1512 	} else {
1513 		cipher_key = &kb[0];
1514 		iv = &kb[64];
1515 	}
1516 	cc->ichapol_in->init(&cc->in.chapol.vtable.in,
1517 		cc->ichacha, cc->ipoly, cipher_key, iv);
1518 	cc->incrypt = 1;
1519 }
1520 
1521 /* see inner.h */
1522 void
1523 br_ssl_engine_switch_chapol_out(br_ssl_engine_context *cc,
1524 	int is_client, int prf_id)
1525 {
1526 	unsigned char kb[88];
1527 	unsigned char *cipher_key, *iv;
1528 
1529 	compute_key_block(cc, prf_id, 44, kb);
1530 	if (is_client) {
1531 		cipher_key = &kb[0];
1532 		iv = &kb[64];
1533 	} else {
1534 		cipher_key = &kb[32];
1535 		iv = &kb[76];
1536 	}
1537 	cc->ichapol_out->init(&cc->out.chapol.vtable.out,
1538 		cc->ichacha, cc->ipoly, cipher_key, iv);
1539 }
1540 
1541 /* see inner.h */
1542 void
1543 br_ssl_engine_switch_ccm_in(br_ssl_engine_context *cc,
1544 	int is_client, int prf_id,
1545 	const br_block_ctrcbc_class *bc_impl,
1546 	size_t cipher_key_len, size_t tag_len)
1547 {
1548 	unsigned char kb[72];
1549 	unsigned char *cipher_key, *iv;
1550 
1551 	compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1552 	if (is_client) {
1553 		cipher_key = &kb[cipher_key_len];
1554 		iv = &kb[(cipher_key_len << 1) + 4];
1555 	} else {
1556 		cipher_key = &kb[0];
1557 		iv = &kb[cipher_key_len << 1];
1558 	}
1559 	cc->iccm_in->init(&cc->in.ccm.vtable.in,
1560 		bc_impl, cipher_key, cipher_key_len, iv, tag_len);
1561 	cc->incrypt = 1;
1562 }
1563 
1564 /* see inner.h */
1565 void
1566 br_ssl_engine_switch_ccm_out(br_ssl_engine_context *cc,
1567 	int is_client, int prf_id,
1568 	const br_block_ctrcbc_class *bc_impl,
1569 	size_t cipher_key_len, size_t tag_len)
1570 {
1571 	unsigned char kb[72];
1572 	unsigned char *cipher_key, *iv;
1573 
1574 	compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1575 	if (is_client) {
1576 		cipher_key = &kb[0];
1577 		iv = &kb[cipher_key_len << 1];
1578 	} else {
1579 		cipher_key = &kb[cipher_key_len];
1580 		iv = &kb[(cipher_key_len << 1) + 4];
1581 	}
1582 	cc->iccm_out->init(&cc->out.ccm.vtable.out,
1583 		bc_impl, cipher_key, cipher_key_len, iv, tag_len);
1584 }
1585