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