File Coverage

src/ssl/ssl_engine.c
Criterion Covered Total %
statement 327 493 66.3
branch 125 240 52.0
condition n/a
subroutine n/a
pod n/a
total 452 733 61.6


line stmt bran cond sub pod time code
1             /*
2             * Copyright (c) 2016 Thomas Pornin
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
70             #include
71             #include
72             #include
73             #endif
74              
75             #if BR_USE_WIN32_RAND
76             #include
77             #include
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 2           br_ssl_engine_fail(br_ssl_engine_context *rc, int err)
288             {
289 2 50         if (rc->iomode != BR_IO_FAILED) {
290 2           rc->iomode = BR_IO_FAILED;
291 2           rc->err = err;
292             }
293 2           }
294              
295             /*
296             * Adjust registers for a new incoming record.
297             */
298             static void
299 16           make_ready_in(br_ssl_engine_context *rc)
300             {
301 16           rc->ixa = rc->ixb = 0;
302 16           rc->ixc = 5;
303 16 50         if (rc->iomode == BR_IO_IN) {
304 0           rc->iomode = BR_IO_INOUT;
305             }
306 16           }
307              
308             /*
309             * Adjust registers for a new outgoing record.
310             */
311             static void
312 17           make_ready_out(br_ssl_engine_context *rc)
313             {
314             size_t a, b;
315              
316 17           a = 5;
317 17           b = rc->obuf_len - a;
318 17           rc->out.vtable->max_plaintext(&rc->out.vtable, &a, &b);
319 17 50         if ((b - a) > rc->max_frag_len) {
320 0           b = a + rc->max_frag_len;
321             }
322 17           rc->oxa = a;
323 17           rc->oxb = b;
324 17           rc->oxc = a;
325 17 50         if (rc->iomode == BR_IO_OUT) {
326 0           rc->iomode = BR_IO_INOUT;
327             }
328 17           }
329              
330             /* see inner.h */
331             void
332 0           br_ssl_engine_new_max_frag_len(br_ssl_engine_context *rc, unsigned max_frag_len)
333             {
334             size_t nxb;
335              
336 0           rc->max_frag_len = max_frag_len;
337 0           nxb = rc->oxc + max_frag_len;
338 0 0         if (rc->oxa < rc->oxb && rc->oxb > nxb && rc->oxa < nxb) {
    0          
    0          
339 0           rc->oxb = nxb;
340             }
341 0           }
342              
343             /* see bearssl_ssl.h */
344             void
345 4           br_ssl_engine_set_buffer(br_ssl_engine_context *rc,
346             void *buf, size_t buf_len, int bidi)
347             {
348 4 100         if (buf == NULL) {
349 2           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 2 50         if (bidi) {
368             size_t w;
369              
370 2 50         if (buf_len < (512 + MAX_IN_OVERHEAD
371             + 512 + MAX_OUT_OVERHEAD))
372             {
373 0           rc->iomode = BR_IO_FAILED;
374 0           rc->err = BR_ERR_BAD_PARAM;
375 0           return;
376 2 50         } else if (buf_len < (16384 + MAX_IN_OVERHEAD
377             + 512 + MAX_OUT_OVERHEAD))
378             {
379 0           w = 512 + MAX_OUT_OVERHEAD;
380             } else {
381 2           w = buf_len - (16384 + MAX_IN_OVERHEAD);
382             }
383 2           br_ssl_engine_set_buffers_bidi(rc,
384             buf, buf_len - w,
385             (unsigned char *)buf + w, w);
386             } else {
387 0           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 4           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 4           rc->iomode = BR_IO_INOUT;
399 4           rc->incrypt = 0;
400 4           rc->err = BR_ERR_OK;
401 4           rc->version_in = 0;
402 4           rc->record_type_in = 0;
403 4           rc->version_out = 0;
404 4           rc->record_type_out = 0;
405 4 100         if (ibuf == NULL) {
406 2 50         if (rc->ibuf == NULL) {
407 0           br_ssl_engine_fail(rc, BR_ERR_BAD_PARAM);
408             }
409             } else {
410             unsigned u;
411              
412 2           rc->ibuf = ibuf;
413 2           rc->ibuf_len = ibuf_len;
414 2 50         if (obuf == NULL) {
415 0           obuf = ibuf;
416 0           obuf_len = ibuf_len;
417             }
418 2           rc->obuf = obuf;
419 2           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 2 50         for (u = 14; u >= 9; u --) {
430             size_t flen;
431              
432 2           flen = (size_t)1 << u;
433 2 50         if (obuf_len >= flen + MAX_OUT_OVERHEAD
434 2 50         && ibuf_len >= flen + MAX_IN_OVERHEAD)
435             {
436 2           break;
437             }
438             }
439 2 50         if (u == 8) {
440 0           br_ssl_engine_fail(rc, BR_ERR_BAD_PARAM);
441 0           return;
442 2 50         } else if (u == 13) {
443 0           u = 12;
444             }
445 2           rc->max_frag_len = (size_t)1 << u;
446 2           rc->log_max_frag_len = u;
447 2           rc->peer_log_max_frag_len = 0;
448             }
449 4           rc->out.vtable = &br_sslrec_out_clear_vtable;
450 4           make_ready_in(rc);
451 4           make_ready_out(rc);
452             }
453              
454             /*
455             * Clear buffers in both directions.
456             */
457             static void
458 2           engine_clearbuf(br_ssl_engine_context *rc)
459             {
460 2           make_ready_in(rc);
461 2           make_ready_out(rc);
462 2           }
463              
464             /*
465             * Make sure the internal PRNG is initialised (but not necessarily
466             * seeded properly yet).
467             */
468             static int
469 2           rng_init(br_ssl_engine_context *cc)
470             {
471             const br_hash_class *h;
472              
473 2 50         if (cc->rng_init_done != 0) {
474 0           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 2           h = br_multihash_getimpl(&cc->mhash, br_sha256_ID);
490 2 50         if (!h) {
491 0           h = br_multihash_getimpl(&cc->mhash, br_sha384_ID);
492 0 0         if (!h) {
493 0           h = br_multihash_getimpl(&cc->mhash,
494             br_sha1_ID);
495 0 0         if (!h) {
496 0           br_ssl_engine_fail(cc, BR_ERR_BAD_STATE);
497 0           return 0;
498             }
499             }
500             }
501 2           br_hmac_drbg_init(&cc->rng, h, NULL, 0);
502 2           cc->rng_init_done = 1;
503 2           return 1;
504             }
505              
506             /* see inner.h */
507             int
508 2           br_ssl_engine_init_rand(br_ssl_engine_context *cc)
509             {
510 2 50         if (!rng_init(cc)) {
511 0           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 2 50         if (!cc->rng_os_rand_done) {
520             br_prng_seeder sd;
521              
522 2           sd = br_prng_seeder_system(NULL);
523 2 50         if (sd != 0 && sd(&cc->rng.vtable)) {
    50          
524 2           cc->rng_init_done = 2;
525             }
526 2           cc->rng_os_rand_done = 1;
527             }
528 2 50         if (cc->rng_init_done < 2) {
529 0           br_ssl_engine_fail(cc, BR_ERR_NO_RANDOM);
530 0           return 0;
531             }
532 2           return 1;
533             }
534              
535             /* see bearssl_ssl.h */
536             void
537 0           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 0 0         if (!rng_init(cc)) {
547 0           return;
548             }
549 0           br_hmac_drbg_update(&cc->rng, data, len);
550 0           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 104           recvrec_buf(const br_ssl_engine_context *rc, size_t *len)
567             {
568 104 100         if (rc->shutdown_recv) {
569 2           *len = 0;
570 2           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 102 50         switch (rc->iomode) {
584 102           case BR_IO_IN:
585             case BR_IO_INOUT:
586 102 100         if (rc->ixa == rc->ixb) {
587             size_t z;
588              
589 100           z = rc->ixc;
590 100 50         if (z > rc->ibuf_len - rc->ixa) {
591 0           z = rc->ibuf_len - rc->ixa;
592             }
593 100           *len = z;
594 100           return rc->ibuf + rc->ixa;
595             }
596 2           break;
597             }
598 2           *len = 0;
599 2           return NULL;
600             }
601              
602             static void
603 22           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 22 50         if (rc->iomode == BR_IO_INOUT && rc->ibuf == rc->obuf) {
    50          
614 0           rc->iomode = BR_IO_IN;
615             }
616              
617             /*
618             * Adjust data pointers.
619             */
620 22           rc->ixb = (rc->ixa += len);
621 22           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 22 50         if (rc->ixa < 5) {
628 16           return;
629             }
630              
631             /*
632             * If we just obtained a full header, process it.
633             */
634 22 100         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 11           rc->record_type_in = rc->ibuf[0];
651 11           version = br_dec16be(rc->ibuf + 1);
652 11 50         if ((version >> 8) != 3) {
653 0           br_ssl_engine_fail(rc, BR_ERR_UNSUPPORTED_VERSION);
654 0           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 11 100         if (rc->version_in != 0 && rc->version_in != version) {
    50          
664 0           br_ssl_engine_fail(rc, BR_ERR_BAD_VERSION);
665 0           return;
666             }
667 11           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 11           rlen = br_dec16be(rc->ibuf + 3);
680 11 100         if (rc->incrypt) {
681 6 50         if (!rc->in.vtable->check_length(
682 6           &rc->in.vtable, rlen))
683             {
684 0           br_ssl_engine_fail(rc, BR_ERR_BAD_LENGTH);
685 0           return;
686             }
687 6 50         if (rlen > (rc->ibuf_len - 5)) {
688 0           br_ssl_engine_fail(rc, BR_ERR_TOO_LARGE);
689 0           return;
690             }
691             } else {
692 5 50         if (rlen > 16384) {
693 0           br_ssl_engine_fail(rc, BR_ERR_BAD_LENGTH);
694 0           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 11 50         if (rlen == 0) {
712 0           make_ready_in(rc);
713             } else {
714 11           rc->ixa = rc->ixb = 5;
715 11           rc->ixc = rlen;
716             }
717 11           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 11 100         if (!rc->incrypt) {
727 5           rc->ixa = 5;
728 5           return;
729             }
730              
731             /*
732             * Since encryption is active, we must wait for a full record
733             * before processing it.
734             */
735 6 50         if (rc->ixc != 0) {
736 0           return;
737             }
738              
739             /*
740             * We got the full record. Decrypt it.
741             */
742 6           pbuf_len = rc->ixa - 5;
743 6           pbuf = rc->in.vtable->decrypt(&rc->in.vtable,
744 6           rc->record_type_in, rc->version_in, rc->ibuf + 5, &pbuf_len);
745 6 50         if (pbuf == 0) {
746 0           br_ssl_engine_fail(rc, BR_ERR_BAD_MAC);
747 0           return;
748             }
749 6           rc->ixa = (size_t)(pbuf - rc->ibuf);
750 6           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 6 50         if (rc->ixa == rc->ixb) {
757 0           make_ready_in(rc);
758             }
759             }
760              
761             /* see inner.h */
762             int
763 4           br_ssl_engine_recvrec_finished(const br_ssl_engine_context *rc)
764             {
765 4 50         switch (rc->iomode) {
766 4           case BR_IO_IN:
767             case BR_IO_INOUT:
768 4 50         return rc->ixc == 0 || rc->ixa < 5;
    0          
769 0           default:
770 0           return 1;
771             }
772             }
773              
774             static unsigned char *
775 67           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 67 50         switch (rc->iomode) {
782 67           case BR_IO_IN:
783             case BR_IO_INOUT:
784 67           *len = rc->ixb - rc->ixa;
785 67 100         return (*len == 0) ? NULL : (rc->ibuf + rc->ixa);
786 0           default:
787 0           *len = 0;
788 0           return NULL;
789             }
790             }
791              
792             static void
793 10           recvpld_ack(br_ssl_engine_context *rc, size_t len)
794             {
795 10           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 10 50         if (rc->ixa == rc->ixb) {
804 10 50         if (rc->ixc == 0) {
805 10           make_ready_in(rc);
806             } else {
807 0           rc->ixa = rc->ixb = 5;
808             }
809             }
810 10           }
811              
812             static unsigned char *
813 72           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 72 50         switch (rc->iomode) {
820 72           case BR_IO_OUT:
821             case BR_IO_INOUT:
822 72           *len = rc->oxb - rc->oxa;
823 72 100         return (*len == 0) ? NULL : (rc->obuf + rc->oxa);
824 0           default:
825 0           *len = 0;
826 0           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 11           sendpld_flush(br_ssl_engine_context *rc, int force)
840             {
841             size_t xlen;
842             unsigned char *buf;
843              
844 11 50         if (rc->oxa == rc->oxb) {
845 0           return;
846             }
847 11           xlen = rc->oxa - rc->oxc;
848 11 50         if (xlen == 0 && !force) {
    0          
849 0           return;
850             }
851 11           buf = rc->out.vtable->encrypt(&rc->out.vtable,
852 11           rc->record_type_out, rc->version_out,
853 11           rc->obuf + rc->oxc, &xlen);
854 11           rc->oxb = rc->oxa = (size_t)(buf - rc->obuf);
855 11           rc->oxc = rc->oxa + xlen;
856             }
857              
858             static void
859 11           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 11 50         if (rc->iomode == BR_IO_INOUT && rc->ibuf == rc->obuf) {
    50          
866 0           rc->iomode = BR_IO_OUT;
867             }
868 11           rc->oxa += len;
869 11 50         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 0           rc->oxb = rc->oxa + 1;
876 0           sendpld_flush(rc, 0);
877             }
878 11           }
879              
880             static unsigned char *
881 93           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 93 50         switch (rc->iomode) {
890 93           case BR_IO_OUT:
891             case BR_IO_INOUT:
892 93 100         if (rc->oxc > rc->oxa) {
893 30           *len = rc->oxc - rc->oxa;
894 30           return rc->obuf + rc->oxa;
895             }
896 63           break;
897             }
898 63           *len = 0;
899 63           return NULL;
900             }
901              
902             static void
903 11           sendrec_ack(br_ssl_engine_context *rc, size_t len)
904             {
905 11           rc->oxb = (rc->oxa += len);
906 11 50         if (rc->oxa == rc->oxc) {
907 11           make_ready_out(rc);
908             }
909 11           }
910              
911             /*
912             * Test whether there is some buffered outgoing record that still must
913             * sent.
914             */
915             static inline int
916 11           has_rec_tosend(const br_ssl_engine_context *rc)
917             {
918 11 50         return rc->oxa == rc->oxb && rc->oxa != rc->oxc;
    0          
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 9           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 9           len = *end - *start;
934 9 50         if (len > 16384) {
935 9           *end = *start + 16384;
936             }
937 9           }
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 5           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 5           buf = (unsigned char *)data - 5;
951 5           buf[0] = record_type;
952 5           br_enc16be(buf + 1, version);
953 5           br_enc16be(buf + 3, *data_len);
954 5           *data_len += 5;
955 5           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 2           br_ssl_engine_set_suites(br_ssl_engine_context *cc,
1021             const uint16_t *suites, size_t suites_num)
1022             {
1023 2 50         if ((suites_num * sizeof *suites) > sizeof cc->suites_buf) {
1024 0           br_ssl_engine_fail(cc, BR_ERR_BAD_PARAM);
1025 0           return;
1026             }
1027 2           memcpy(cc->suites_buf, suites, suites_num * sizeof *suites);
1028 2           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 20           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 8           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 28           cc->hbuf_in = recvpld_buf(cc, &hlen_in);
1054 28 100         if (cc->hbuf_in != NULL
1055 9 50         && cc->record_type_in == BR_SSL_APPLICATION_DATA)
1056             {
1057 0           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 28           cc->saved_hbuf_out = cc->hbuf_out = sendpld_buf(cc, &hlen_out);
1067 28 100         if (cc->hbuf_out != NULL && br_ssl_engine_has_pld_to_send(cc)) {
    50          
1068 0           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 28           cc->hlen_in = hlen_in;
1078 28           cc->hlen_out = hlen_out;
1079 28           cc->action = action;
1080 28           cc->hsrun(&cc->cpu);
1081 28 100         if (br_ssl_engine_closed(cc)) {
1082 2           return;
1083             }
1084 26 50         if (cc->hbuf_out != cc->saved_hbuf_out) {
1085 0           sendpld_ack(cc, cc->hbuf_out - cc->saved_hbuf_out);
1086             }
1087 26 100         if (hlen_in != cc->hlen_in) {
1088 8           recvpld_ack(cc, hlen_in - cc->hlen_in);
1089 8 50         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 8           action = 0;
1098 8           continue;
1099             }
1100             }
1101 18           break;
1102             }
1103             }
1104              
1105             /* see inner.h */
1106             void
1107 14           br_ssl_engine_flush_record(br_ssl_engine_context *cc)
1108             {
1109 14 100         if (cc->hbuf_out != cc->saved_hbuf_out) {
1110 9           sendpld_ack(cc, cc->hbuf_out - cc->saved_hbuf_out);
1111             }
1112 14 100         if (br_ssl_engine_has_pld_to_send(cc)) {
1113 9           sendpld_flush(cc, 0);
1114             }
1115 14           cc->saved_hbuf_out = cc->hbuf_out = sendpld_buf(cc, &cc->hlen_out);
1116 14           }
1117              
1118             /* see bearssl_ssl.h */
1119             unsigned char *
1120 84           br_ssl_engine_sendapp_buf(const br_ssl_engine_context *cc, size_t *len)
1121             {
1122 84 100         if (!(cc->application_data & 1)) {
1123 54           *len = 0;
1124 54           return NULL;
1125             }
1126 30           return sendpld_buf(cc, len);
1127             }
1128              
1129             /* see bearssl_ssl.h */
1130             void
1131 2           br_ssl_engine_sendapp_ack(br_ssl_engine_context *cc, size_t len)
1132             {
1133 2           sendpld_ack(cc, len);
1134 2           }
1135              
1136             /* see bearssl_ssl.h */
1137             unsigned char *
1138 85           br_ssl_engine_recvapp_buf(const br_ssl_engine_context *cc, size_t *len)
1139             {
1140 85 100         if (!(cc->application_data & 1)
1141 31 100         || cc->record_type_in != BR_SSL_APPLICATION_DATA)
1142             {
1143 68           *len = 0;
1144 68           return NULL;
1145             }
1146 17           return recvpld_buf(cc, len);
1147             }
1148              
1149             /* see bearssl_ssl.h */
1150             void
1151 2           br_ssl_engine_recvapp_ack(br_ssl_engine_context *cc, size_t len)
1152             {
1153 2           recvpld_ack(cc, len);
1154 2           }
1155              
1156             /* see bearssl_ssl.h */
1157             unsigned char *
1158 93           br_ssl_engine_sendrec_buf(const br_ssl_engine_context *cc, size_t *len)
1159             {
1160 93           return sendrec_buf(cc, len);
1161             }
1162              
1163             /* see bearssl_ssl.h */
1164             void
1165 11           br_ssl_engine_sendrec_ack(br_ssl_engine_context *cc, size_t len)
1166             {
1167 11           sendrec_ack(cc, len);
1168 11 50         if (len != 0 && !has_rec_tosend(cc)
    50          
1169 11 100         && (cc->record_type_out != BR_SSL_APPLICATION_DATA
1170 3 50         || (cc->application_data & 1) == 0))
1171             {
1172 8           jump_handshake(cc, 0);
1173             }
1174 11           }
1175              
1176             /* see bearssl_ssl.h */
1177             unsigned char *
1178 104           br_ssl_engine_recvrec_buf(const br_ssl_engine_context *cc, size_t *len)
1179             {
1180 104           return recvrec_buf(cc, len);
1181             }
1182              
1183             /* see bearssl_ssl.h */
1184             void
1185 22           br_ssl_engine_recvrec_ack(br_ssl_engine_context *cc, size_t len)
1186             {
1187             unsigned char *buf;
1188              
1189 22           recvrec_ack(cc, len);
1190 22 50         if (br_ssl_engine_closed(cc)) {
1191 0           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 22           buf = recvpld_buf(cc, &len);
1200 22 100         if (buf != NULL) {
1201 11           switch (cc->record_type_in) {
1202 9           case BR_SSL_CHANGE_CIPHER_SPEC:
1203             case BR_SSL_ALERT:
1204             case BR_SSL_HANDSHAKE:
1205 9           jump_handshake(cc, 0);
1206 9           break;
1207 2           case BR_SSL_APPLICATION_DATA:
1208 2 50         if (cc->application_data == 1) {
1209 2           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 0 0         if (cc->application_data == 2) {
1218 0           recvpld_ack(cc, len);
1219 0           break;
1220             }
1221              
1222             /* Fall through */
1223             default:
1224 0           br_ssl_engine_fail(cc, BR_ERR_UNEXPECTED);
1225 0           break;
1226             }
1227             }
1228             }
1229              
1230             /* see bearssl_ssl.h */
1231             void
1232 1           br_ssl_engine_close(br_ssl_engine_context *cc)
1233             {
1234 1 50         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 1 50         if (br_ssl_engine_recvapp_buf(cc, &len) != NULL && len != 0) {
    0          
1248 0           br_ssl_engine_recvapp_ack(cc, len);
1249             }
1250 1           jump_handshake(cc, 1);
1251             }
1252 1           }
1253              
1254             /* see bearssl_ssl.h */
1255             int
1256 0           br_ssl_engine_renegotiate(br_ssl_engine_context *cc)
1257             {
1258             size_t len;
1259              
1260 0 0         if (br_ssl_engine_closed(cc) || cc->reneg == 1
    0          
1261 0 0         || (cc->flags & BR_OPT_NO_RENEGOTIATION) != 0
1262 0 0         || br_ssl_engine_recvapp_buf(cc, &len) != NULL)
1263             {
1264 0           return 0;
1265             }
1266 0           jump_handshake(cc, 2);
1267 0           return 1;
1268             }
1269              
1270             /* see bearssl.h */
1271             unsigned
1272 86           br_ssl_engine_current_state(const br_ssl_engine_context *cc)
1273             {
1274             unsigned s;
1275             size_t len;
1276              
1277 86 100         if (br_ssl_engine_closed(cc)) {
1278 4           return BR_SSL_CLOSED;
1279             }
1280              
1281 82           s = 0;
1282 82 100         if (br_ssl_engine_sendrec_buf(cc, &len) != NULL) {
1283 19           s |= BR_SSL_SENDREC;
1284             }
1285 82 100         if (br_ssl_engine_recvrec_buf(cc, &len) != NULL) {
1286 78           s |= BR_SSL_RECVREC;
1287             }
1288 82 100         if (br_ssl_engine_sendapp_buf(cc, &len) != NULL) {
1289 25           s |= BR_SSL_SENDAPP;
1290             }
1291 82 100         if (br_ssl_engine_recvapp_buf(cc, &len) != NULL) {
1292 2           s |= BR_SSL_RECVAPP;
1293             }
1294 82           return s;
1295             }
1296              
1297             /* see bearssl_ssl.h */
1298             void
1299 8           br_ssl_engine_flush(br_ssl_engine_context *cc, int force)
1300             {
1301 8 50         if (!br_ssl_engine_closed(cc) && (cc->application_data & 1) != 0) {
    100          
1302 2           sendpld_flush(cc, force);
1303             }
1304 8           }
1305              
1306             /* see inner.h */
1307             void
1308 2           br_ssl_engine_hs_reset(br_ssl_engine_context *cc,
1309             void (*hsinit)(void *), void (*hsrun)(void *))
1310             {
1311 2           engine_clearbuf(cc);
1312 2           cc->cpu.dp = cc->dp_stack;
1313 2           cc->cpu.rp = cc->rp_stack;
1314 2           hsinit(&cc->cpu);
1315 2           cc->hsrun = hsrun;
1316 2           cc->shutdown_recv = 0;
1317 2           cc->application_data = 0;
1318 2           cc->alert = 0;
1319 2           jump_handshake(cc, 0);
1320 2           }
1321              
1322             /* see inner.h */
1323             br_tls_prf_impl
1324 10           br_ssl_engine_get_PRF(br_ssl_engine_context *cc, int prf_id)
1325             {
1326 10 50         if (cc->session.version >= BR_TLS12) {
1327 10 50         if (prf_id == br_sha384_ID) {
1328 0           return cc->prf_sha384;
1329             } else {
1330 10           return cc->prf_sha256;
1331             }
1332             } else {
1333 0           return cc->prf10;
1334             }
1335             }
1336              
1337             /* see inner.h */
1338             void
1339 2           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 2           br_tls_prf_seed_chunk seed[2] = {
1344 2           { cc->client_random, sizeof cc->client_random },
1345 2           { cc->server_random, sizeof cc->server_random }
1346             };
1347              
1348 2           iprf = br_ssl_engine_get_PRF(cc, prf_id);
1349 2           iprf(cc->session.master_secret, sizeof cc->session.master_secret,
1350             pms, pms_len, "master secret", 2, seed);
1351 2           }
1352              
1353             /*
1354             * Compute key block.
1355             */
1356             static void
1357 4           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 4           br_tls_prf_seed_chunk seed[2] = {
1362 4           { cc->server_random, sizeof cc->server_random },
1363 4           { cc->client_random, sizeof cc->client_random }
1364             };
1365              
1366 4           iprf = br_ssl_engine_get_PRF(cc, prf_id);
1367 4           iprf(kb, half_len << 1,
1368 4           cc->session.master_secret, sizeof cc->session.master_secret,
1369             "key expansion", 2, seed);
1370 4           }
1371              
1372             /* see inner.h */
1373             void
1374 0           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 0           imh = br_ssl_engine_get_hash(cc, mac_id);
1384 0           mac_out_len = (imh->desc >> BR_HASHDESC_OUT_OFF) & BR_HASHDESC_OUT_MASK;
1385 0           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 0 0         if (cc->session.version >= BR_TLS11) {
1391 0           iv_len = 0;
1392             } else {
1393 0           iv_len = bc_impl->block_size;
1394             }
1395 0           compute_key_block(cc, prf_id,
1396 0           mac_key_len + cipher_key_len + iv_len, kb);
1397 0 0         if (is_client) {
1398 0           mac_key = &kb[mac_key_len];
1399 0           cipher_key = &kb[(mac_key_len << 1) + cipher_key_len];
1400 0           iv = &kb[((mac_key_len + cipher_key_len) << 1) + iv_len];
1401             } else {
1402 0           mac_key = &kb[0];
1403 0           cipher_key = &kb[mac_key_len << 1];
1404 0           iv = &kb[(mac_key_len + cipher_key_len) << 1];
1405             }
1406 0 0         if (iv_len == 0) {
1407 0           iv = NULL;
1408             }
1409 0           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 0           cc->incrypt = 1;
1413 0           }
1414              
1415             /* see inner.h */
1416             void
1417 0           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 0           imh = br_ssl_engine_get_hash(cc, mac_id);
1427 0           mac_out_len = (imh->desc >> BR_HASHDESC_OUT_OFF) & BR_HASHDESC_OUT_MASK;
1428 0           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 0 0         if (cc->session.version >= BR_TLS11) {
1434 0           iv_len = 0;
1435             } else {
1436 0           iv_len = bc_impl->block_size;
1437             }
1438 0           compute_key_block(cc, prf_id,
1439 0           mac_key_len + cipher_key_len + iv_len, kb);
1440 0 0         if (is_client) {
1441 0           mac_key = &kb[0];
1442 0           cipher_key = &kb[mac_key_len << 1];
1443 0           iv = &kb[(mac_key_len + cipher_key_len) << 1];
1444             } else {
1445 0           mac_key = &kb[mac_key_len];
1446 0           cipher_key = &kb[(mac_key_len << 1) + cipher_key_len];
1447 0           iv = &kb[((mac_key_len + cipher_key_len) << 1) + iv_len];
1448             }
1449 0 0         if (iv_len == 0) {
1450 0           iv = NULL;
1451             }
1452 0           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 0           }
1456              
1457             /* see inner.h */
1458             void
1459 0           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 0           compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1467 0 0         if (is_client) {
1468 0           cipher_key = &kb[cipher_key_len];
1469 0           iv = &kb[(cipher_key_len << 1) + 4];
1470             } else {
1471 0           cipher_key = &kb[0];
1472 0           iv = &kb[cipher_key_len << 1];
1473             }
1474 0           cc->igcm_in->init(&cc->in.gcm.vtable.in,
1475             bc_impl, cipher_key, cipher_key_len, cc->ighash, iv);
1476 0           cc->incrypt = 1;
1477 0           }
1478              
1479             /* see inner.h */
1480             void
1481 0           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 0           compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1489 0 0         if (is_client) {
1490 0           cipher_key = &kb[0];
1491 0           iv = &kb[cipher_key_len << 1];
1492             } else {
1493 0           cipher_key = &kb[cipher_key_len];
1494 0           iv = &kb[(cipher_key_len << 1) + 4];
1495             }
1496 0           cc->igcm_out->init(&cc->out.gcm.vtable.out,
1497             bc_impl, cipher_key, cipher_key_len, cc->ighash, iv);
1498 0           }
1499              
1500             /* see inner.h */
1501             void
1502 2           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 2           compute_key_block(cc, prf_id, 44, kb);
1509 2 100         if (is_client) {
1510 1           cipher_key = &kb[32];
1511 1           iv = &kb[76];
1512             } else {
1513 1           cipher_key = &kb[0];
1514 1           iv = &kb[64];
1515             }
1516 2           cc->ichapol_in->init(&cc->in.chapol.vtable.in,
1517             cc->ichacha, cc->ipoly, cipher_key, iv);
1518 2           cc->incrypt = 1;
1519 2           }
1520              
1521             /* see inner.h */
1522             void
1523 2           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 2           compute_key_block(cc, prf_id, 44, kb);
1530 2 100         if (is_client) {
1531 1           cipher_key = &kb[0];
1532 1           iv = &kb[64];
1533             } else {
1534 1           cipher_key = &kb[32];
1535 1           iv = &kb[76];
1536             }
1537 2           cc->ichapol_out->init(&cc->out.chapol.vtable.out,
1538             cc->ichacha, cc->ipoly, cipher_key, iv);
1539 2           }
1540              
1541             /* see inner.h */
1542             void
1543 0           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 0           compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1552 0 0         if (is_client) {
1553 0           cipher_key = &kb[cipher_key_len];
1554 0           iv = &kb[(cipher_key_len << 1) + 4];
1555             } else {
1556 0           cipher_key = &kb[0];
1557 0           iv = &kb[cipher_key_len << 1];
1558             }
1559 0           cc->iccm_in->init(&cc->in.ccm.vtable.in,
1560             bc_impl, cipher_key, cipher_key_len, iv, tag_len);
1561 0           cc->incrypt = 1;
1562 0           }
1563              
1564             /* see inner.h */
1565             void
1566 0           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 0           compute_key_block(cc, prf_id, cipher_key_len + 4, kb);
1575 0 0         if (is_client) {
1576 0           cipher_key = &kb[0];
1577 0           iv = &kb[cipher_key_len << 1];
1578             } else {
1579 0           cipher_key = &kb[cipher_key_len];
1580 0           iv = &kb[(cipher_key_len << 1) + 4];
1581             }
1582 0           cc->iccm_out->init(&cc->out.ccm.vtable.out,
1583             bc_impl, cipher_key, cipher_key_len, iv, tag_len);
1584 0           }