]> git.ipfire.org Git - thirdparty/openssl.git/blob - ssl/record/rec_layer_s3.c
16247031bb19679856f588099554c2ab0e43803f
[thirdparty/openssl.git] / ssl / record / rec_layer_s3.c
1 /*
2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <stdio.h>
11 #include <limits.h>
12 #include <errno.h>
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include <openssl/core_names.h>
18 #include "record_local.h"
19 #include "internal/packet.h"
20
21 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
22 !( defined(AES_ASM) && ( \
23 defined(__x86_64) || defined(__x86_64__) || \
24 defined(_M_AMD64) || defined(_M_X64) ) \
25 )
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
28 #endif
29
30 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
31 {
32 rl->s = s;
33 }
34
35 void RECORD_LAYER_clear(RECORD_LAYER *rl)
36 {
37 rl->rstate = SSL_ST_READ_HEADER;
38
39 rl->wnum = 0;
40 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
41 rl->handshake_fragment_len = 0;
42 rl->wpend_tot = 0;
43 rl->wpend_type = 0;
44 rl->wpend_ret = 0;
45 rl->wpend_buf = NULL;
46
47 ssl3_release_write_buffer(rl->s);
48
49 RECORD_LAYER_reset_read_sequence(rl);
50 RECORD_LAYER_reset_write_sequence(rl);
51
52 if (rl->rrlmethod != NULL)
53 rl->rrlmethod->free(rl->rrl); /* Ignore return value */
54 BIO_free(rl->rrlnext);
55 rl->rrlmethod = NULL;
56 rl->rrlnext = NULL;
57
58 if (rl->d)
59 DTLS_RECORD_LAYER_clear(rl);
60 }
61
62 void RECORD_LAYER_release(RECORD_LAYER *rl)
63 {
64 if (rl->numwpipes > 0)
65 ssl3_release_write_buffer(rl->s);
66 }
67
68 /* Checks if we have unprocessed read ahead data pending */
69 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
70 {
71 return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
72 }
73
74 /* Checks if we have decrypted unread record data pending */
75 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
76 {
77 return (rl->curr_rec < rl->num_recs)
78 || rl->rrlmethod->processed_read_pending(rl->rrl);
79 }
80
81 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
82 {
83 return (rl->numwpipes > 0)
84 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
85 }
86
87 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
88 {
89 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
90 }
91
92 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
93 {
94 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
95 }
96
97 size_t ssl3_pending(const SSL *s)
98 {
99 size_t i, num = 0;
100 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
101
102 if (sc == NULL)
103 return 0;
104
105 if (SSL_CONNECTION_IS_DTLS(sc)) {
106 TLS_RECORD *rdata;
107 pitem *item, *iter;
108
109 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
110 while ((item = pqueue_next(&iter)) != NULL) {
111 rdata = item->data;
112 num += rdata->length;
113 }
114 }
115
116 for (i = 0; i < sc->rlayer.num_recs; i++) {
117 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
118 return num;
119 num += sc->rlayer.tlsrecs[i].length;
120 }
121
122 num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
123
124 return num;
125 }
126
127 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
128 {
129 ctx->default_read_buf_len = len;
130 }
131
132 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
133 {
134 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
135
136 if (sc == NULL)
137 return;
138 sc->rlayer.default_read_buf_len = len;
139 }
140
141 const char *SSL_rstate_string_long(const SSL *s)
142 {
143 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
144
145 if (sc == NULL)
146 return NULL;
147
148 /* TODO(RECLAYER): Fix me */
149 switch (sc->rlayer.rstate) {
150 case SSL_ST_READ_HEADER:
151 return "read header";
152 case SSL_ST_READ_BODY:
153 return "read body";
154 case SSL_ST_READ_DONE:
155 return "read done";
156 default:
157 return "unknown";
158 }
159 }
160
161 const char *SSL_rstate_string(const SSL *s)
162 {
163 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
164
165 if (sc == NULL)
166 return NULL;
167
168 /* TODO(RECLAYER): Fix me */
169 switch (sc->rlayer.rstate) {
170 case SSL_ST_READ_HEADER:
171 return "RH";
172 case SSL_ST_READ_BODY:
173 return "RB";
174 case SSL_ST_READ_DONE:
175 return "RD";
176 default:
177 return "unknown";
178 }
179 }
180
181
182 /*
183 * Call this to write data in records of type 'type' It will return <= 0 if
184 * not all data has been sent or non-blocking IO.
185 */
186 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
187 size_t *written)
188 {
189 const unsigned char *buf = buf_;
190 size_t tot;
191 size_t n, max_send_fragment, split_send_fragment, maxpipes;
192 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
193 size_t nw;
194 #endif
195 SSL3_BUFFER *wb;
196 int i;
197 size_t tmpwrit;
198 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
199
200 if (s == NULL)
201 return -1;
202
203 wb = &s->rlayer.wbuf[0];
204 s->rwstate = SSL_NOTHING;
205 tot = s->rlayer.wnum;
206 /*
207 * ensure that if we end up with a smaller value of data to write out
208 * than the original len from a write which didn't complete for
209 * non-blocking I/O and also somehow ended up avoiding the check for
210 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
211 * possible to end up with (len-tot) as a large number that will then
212 * promptly send beyond the end of the users buffer ... so we trap and
213 * report the error in a way the user will notice
214 */
215 if ((len < s->rlayer.wnum)
216 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
217 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
218 return -1;
219 }
220
221 if (s->early_data_state == SSL_EARLY_DATA_WRITING
222 && !ossl_early_data_count_ok(s, len, 0, 1)) {
223 /* SSLfatal() already called */
224 return -1;
225 }
226
227 s->rlayer.wnum = 0;
228
229 /*
230 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
231 * into init unless we have writes pending - in which case we should finish
232 * doing that first.
233 */
234 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
235 || s->ext.extra_tickets_expected > 0))
236 ossl_statem_set_in_init(s, 1);
237
238 /*
239 * When writing early data on the server side we could be "in_init" in
240 * between receiving the EoED and the CF - but we don't want to handle those
241 * messages yet.
242 */
243 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
244 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
245 i = s->handshake_func(ssl);
246 /* SSLfatal() already called */
247 if (i < 0)
248 return i;
249 if (i == 0) {
250 return -1;
251 }
252 }
253
254 /*
255 * first check if there is a SSL3_BUFFER still being written out. This
256 * will happen with non blocking IO
257 */
258 if (wb->left != 0) {
259 /* SSLfatal() already called if appropriate */
260 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
261 &tmpwrit);
262 if (i <= 0) {
263 /* XXX should we ssl3_release_write_buffer if i<0? */
264 s->rlayer.wnum = tot;
265 return i;
266 }
267 tot += tmpwrit; /* this might be last fragment */
268 }
269 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
270 /*
271 * Depending on platform multi-block can deliver several *times*
272 * better performance. Downside is that it has to allocate
273 * jumbo buffer to accommodate up to 8 records, but the
274 * compromise is considered worthy.
275 */
276 if (type == SSL3_RT_APPLICATION_DATA
277 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
278 && s->compress == NULL
279 && s->msg_callback == NULL
280 && !SSL_WRITE_ETM(s)
281 && SSL_USE_EXPLICIT_IV(s)
282 && !BIO_get_ktls_send(s->wbio)
283 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
284 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
285 unsigned char aad[13];
286 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
287 size_t packlen;
288 int packleni;
289
290 /* minimize address aliasing conflicts */
291 if ((max_send_fragment & 0xfff) == 0)
292 max_send_fragment -= 512;
293
294 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
295 ssl3_release_write_buffer(s);
296
297 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
298 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
299 (int)max_send_fragment, NULL);
300
301 if (len >= 8 * max_send_fragment)
302 packlen *= 8;
303 else
304 packlen *= 4;
305
306 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
307 /* SSLfatal() already called */
308 return -1;
309 }
310 } else if (tot == len) { /* done? */
311 /* free jumbo buffer */
312 ssl3_release_write_buffer(s);
313 *written = tot;
314 return 1;
315 }
316
317 n = (len - tot);
318 for (;;) {
319 if (n < 4 * max_send_fragment) {
320 /* free jumbo buffer */
321 ssl3_release_write_buffer(s);
322 break;
323 }
324
325 if (s->s3.alert_dispatch) {
326 i = ssl->method->ssl_dispatch_alert(ssl);
327 if (i <= 0) {
328 /* SSLfatal() already called if appropriate */
329 s->rlayer.wnum = tot;
330 return i;
331 }
332 }
333
334 if (n >= 8 * max_send_fragment)
335 nw = max_send_fragment * (mb_param.interleave = 8);
336 else
337 nw = max_send_fragment * (mb_param.interleave = 4);
338
339 memcpy(aad, s->rlayer.write_sequence, 8);
340 aad[8] = type;
341 aad[9] = (unsigned char)(s->version >> 8);
342 aad[10] = (unsigned char)(s->version);
343 aad[11] = 0;
344 aad[12] = 0;
345 mb_param.out = NULL;
346 mb_param.inp = aad;
347 mb_param.len = nw;
348
349 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
350 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
351 sizeof(mb_param), &mb_param);
352 packlen = (size_t)packleni;
353 if (packleni <= 0 || packlen > wb->len) { /* never happens */
354 /* free jumbo buffer */
355 ssl3_release_write_buffer(s);
356 break;
357 }
358
359 mb_param.out = wb->buf;
360 mb_param.inp = &buf[tot];
361 mb_param.len = nw;
362
363 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
364 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
365 sizeof(mb_param), &mb_param) <= 0)
366 return -1;
367
368 s->rlayer.write_sequence[7] += mb_param.interleave;
369 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
370 int j = 6;
371 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
372 }
373
374 wb->offset = 0;
375 wb->left = packlen;
376
377 s->rlayer.wpend_tot = nw;
378 s->rlayer.wpend_buf = &buf[tot];
379 s->rlayer.wpend_type = type;
380 s->rlayer.wpend_ret = nw;
381
382 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
383 if (i <= 0) {
384 /* SSLfatal() already called if appropriate */
385 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
386 /* free jumbo buffer */
387 ssl3_release_write_buffer(s);
388 }
389 s->rlayer.wnum = tot;
390 return i;
391 }
392 if (tmpwrit == n) {
393 /* free jumbo buffer */
394 ssl3_release_write_buffer(s);
395 *written = tot + tmpwrit;
396 return 1;
397 }
398 n -= tmpwrit;
399 tot += tmpwrit;
400 }
401 } else
402 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
403 if (tot == len) { /* done? */
404 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
405 ssl3_release_write_buffer(s);
406
407 *written = tot;
408 return 1;
409 }
410
411 n = (len - tot);
412
413 max_send_fragment = ssl_get_max_send_fragment(s);
414 split_send_fragment = ssl_get_split_send_fragment(s);
415 /*
416 * If max_pipelines is 0 then this means "undefined" and we default to
417 * 1 pipeline. Similarly if the cipher does not support pipelined
418 * processing then we also only use 1 pipeline, or if we're not using
419 * explicit IVs
420 */
421 maxpipes = s->max_pipelines;
422 if (maxpipes > SSL_MAX_PIPELINES) {
423 /*
424 * We should have prevented this when we set max_pipelines so we
425 * shouldn't get here
426 */
427 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
428 return -1;
429 }
430 if (maxpipes == 0
431 || s->enc_write_ctx == NULL
432 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
433 & EVP_CIPH_FLAG_PIPELINE) == 0
434 || !SSL_USE_EXPLICIT_IV(s))
435 maxpipes = 1;
436 if (max_send_fragment == 0
437 || split_send_fragment == 0
438 || split_send_fragment > max_send_fragment) {
439 /*
440 * We should have prevented this when we set/get the split and max send
441 * fragments so we shouldn't get here
442 */
443 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
444 return -1;
445 }
446
447 for (;;) {
448 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
449 size_t numpipes, j;
450
451 if (n == 0)
452 numpipes = 1;
453 else
454 numpipes = ((n - 1) / split_send_fragment) + 1;
455 if (numpipes > maxpipes)
456 numpipes = maxpipes;
457
458 if (n / numpipes >= max_send_fragment) {
459 /*
460 * We have enough data to completely fill all available
461 * pipelines
462 */
463 for (j = 0; j < numpipes; j++) {
464 pipelens[j] = max_send_fragment;
465 }
466 } else {
467 /* We can partially fill all available pipelines */
468 tmppipelen = n / numpipes;
469 remain = n % numpipes;
470 for (j = 0; j < numpipes; j++) {
471 pipelens[j] = tmppipelen;
472 if (j < remain)
473 pipelens[j]++;
474 }
475 }
476
477 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
478 &tmpwrit);
479 if (i <= 0) {
480 /* SSLfatal() already called if appropriate */
481 /* XXX should we ssl3_release_write_buffer if i<0? */
482 s->rlayer.wnum = tot;
483 return i;
484 }
485
486 if (tmpwrit == n ||
487 (type == SSL3_RT_APPLICATION_DATA &&
488 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
489 /*
490 * next chunk of data should get another prepended empty fragment
491 * in ciphersuites with known-IV weakness:
492 */
493 s->s3.empty_fragment_done = 0;
494
495 if (tmpwrit == n
496 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
497 && !SSL_CONNECTION_IS_DTLS(s))
498 ssl3_release_write_buffer(s);
499
500 *written = tot + tmpwrit;
501 return 1;
502 }
503
504 n -= tmpwrit;
505 tot += tmpwrit;
506 }
507 }
508
509 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
510 size_t *pipelens, size_t numpipes,
511 int create_empty_fragment, size_t *written)
512 {
513 WPACKET pkt[SSL_MAX_PIPELINES];
514 SSL3_RECORD wr[SSL_MAX_PIPELINES];
515 WPACKET *thispkt;
516 SSL3_RECORD *thiswr;
517 unsigned char *recordstart;
518 int i, mac_size, clear = 0;
519 size_t prefix_len = 0;
520 int eivlen = 0;
521 size_t align = 0;
522 SSL3_BUFFER *wb;
523 SSL_SESSION *sess;
524 size_t totlen = 0, len, wpinited = 0;
525 size_t j;
526 int using_ktls;
527 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
528
529 for (j = 0; j < numpipes; j++)
530 totlen += pipelens[j];
531 /*
532 * first check if there is a SSL3_BUFFER still being written out. This
533 * will happen with non blocking IO
534 */
535 if (RECORD_LAYER_write_pending(&s->rlayer)) {
536 /* Calls SSLfatal() as required */
537 return ssl3_write_pending(s, type, buf, totlen, written);
538 }
539
540 /* If we have an alert to send, lets send it */
541 if (s->s3.alert_dispatch) {
542 i = ssl->method->ssl_dispatch_alert(ssl);
543 if (i <= 0) {
544 /* SSLfatal() already called if appropriate */
545 return i;
546 }
547 /* if it went, fall through and send more stuff */
548 }
549
550 if (s->rlayer.numwpipes < numpipes) {
551 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
552 /* SSLfatal() already called */
553 return -1;
554 }
555 }
556
557 if (totlen == 0 && !create_empty_fragment)
558 return 0;
559
560 sess = s->session;
561
562 if ((sess == NULL)
563 || (s->enc_write_ctx == NULL)
564 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
565 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
566 mac_size = 0;
567 } else {
568 mac_size = EVP_MD_CTX_get_size(s->write_hash);
569 if (mac_size < 0) {
570 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
571 goto err;
572 }
573 }
574
575 /*
576 * 'create_empty_fragment' is true only when this function calls itself
577 */
578 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
579 /*
580 * countermeasure against known-IV weakness in CBC ciphersuites (see
581 * http://www.openssl.org/~bodo/tls-cbc.txt)
582 */
583
584 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
585 /*
586 * recursive function call with 'create_empty_fragment' set; this
587 * prepares and buffers the data for an empty fragment (these
588 * 'prefix_len' bytes are sent out later together with the actual
589 * payload)
590 */
591 size_t tmppipelen = 0;
592 int ret;
593
594 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
595 if (ret <= 0) {
596 /* SSLfatal() already called if appropriate */
597 goto err;
598 }
599
600 if (prefix_len >
601 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
602 /* insufficient space */
603 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
604 goto err;
605 }
606 }
607
608 s->s3.empty_fragment_done = 1;
609 }
610
611 using_ktls = BIO_get_ktls_send(s->wbio);
612 if (using_ktls) {
613 /*
614 * ktls doesn't modify the buffer, but to avoid a warning we need to
615 * discard the const qualifier.
616 * This doesn't leak memory because the buffers have been released when
617 * switching to ktls.
618 */
619 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
620 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
621 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
622 goto wpacket_init_complete;
623 }
624
625 if (create_empty_fragment) {
626 wb = &s->rlayer.wbuf[0];
627 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
628 /*
629 * extra fragment would be couple of cipher blocks, which would be
630 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
631 * payload, then we can just pretend we simply have two headers.
632 */
633 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
634 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
635 #endif
636 SSL3_BUFFER_set_offset(wb, align);
637 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
638 SSL3_BUFFER_get_len(wb), 0)
639 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
640 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
641 goto err;
642 }
643 wpinited = 1;
644 } else if (prefix_len) {
645 wb = &s->rlayer.wbuf[0];
646 if (!WPACKET_init_static_len(&pkt[0],
647 SSL3_BUFFER_get_buf(wb),
648 SSL3_BUFFER_get_len(wb), 0)
649 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
650 + prefix_len, NULL)) {
651 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
652 goto err;
653 }
654 wpinited = 1;
655 } else {
656 for (j = 0; j < numpipes; j++) {
657 thispkt = &pkt[j];
658
659 wb = &s->rlayer.wbuf[j];
660 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
661 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
662 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
663 #endif
664 SSL3_BUFFER_set_offset(wb, align);
665 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
666 SSL3_BUFFER_get_len(wb), 0)
667 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
668 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
669 goto err;
670 }
671 wpinited++;
672 }
673 }
674
675 /* Explicit IV length, block ciphers appropriate version flag */
676 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
677 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
678 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
679 if (mode == EVP_CIPH_CBC_MODE) {
680 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
681 if (eivlen < 0) {
682 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
683 goto err;
684 }
685 if (eivlen <= 1)
686 eivlen = 0;
687 } else if (mode == EVP_CIPH_GCM_MODE) {
688 /* Need explicit part of IV for GCM mode */
689 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
690 } else if (mode == EVP_CIPH_CCM_MODE) {
691 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
692 }
693 }
694
695 wpacket_init_complete:
696
697 totlen = 0;
698 /* Clear our SSL3_RECORD structures */
699 memset(wr, 0, sizeof(wr));
700 for (j = 0; j < numpipes; j++) {
701 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
702 : s->version;
703 unsigned char *compressdata = NULL;
704 size_t maxcomplen;
705 unsigned int rectype;
706
707 thispkt = &pkt[j];
708 thiswr = &wr[j];
709
710 /*
711 * In TLSv1.3, once encrypting, we always use application data for the
712 * record type
713 */
714 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
715 && s->enc_write_ctx != NULL
716 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
717 || type != SSL3_RT_ALERT))
718 rectype = SSL3_RT_APPLICATION_DATA;
719 else
720 rectype = type;
721 SSL3_RECORD_set_type(thiswr, rectype);
722
723 /*
724 * Some servers hang if initial client hello is larger than 256 bytes
725 * and record version number > TLS 1.0
726 */
727 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
728 && !s->renegotiate
729 && TLS1_get_version(ssl) > TLS1_VERSION
730 && s->hello_retry_request == SSL_HRR_NONE)
731 version = TLS1_VERSION;
732 SSL3_RECORD_set_rec_version(thiswr, version);
733
734 maxcomplen = pipelens[j];
735 if (s->compress != NULL)
736 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
737
738 /*
739 * When using offload kernel will write the header.
740 * Otherwise write the header now
741 */
742 if (!using_ktls
743 && (!WPACKET_put_bytes_u8(thispkt, rectype)
744 || !WPACKET_put_bytes_u16(thispkt, version)
745 || !WPACKET_start_sub_packet_u16(thispkt)
746 || (eivlen > 0
747 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
748 || (maxcomplen > 0
749 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
750 &compressdata)))) {
751 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
752 goto err;
753 }
754
755 /* lets setup the record stuff. */
756 SSL3_RECORD_set_data(thiswr, compressdata);
757 SSL3_RECORD_set_length(thiswr, pipelens[j]);
758 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
759 totlen += pipelens[j];
760
761 /*
762 * we now 'read' from thiswr->input, thiswr->length bytes into
763 * thiswr->data
764 */
765
766 /* first we compress */
767 if (s->compress != NULL) {
768 if (!ssl3_do_compress(s, thiswr)
769 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
770 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
771 goto err;
772 }
773 } else {
774 if (using_ktls) {
775 SSL3_RECORD_reset_data(&wr[j]);
776 } else {
777 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
778 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
779 goto err;
780 }
781 SSL3_RECORD_reset_input(&wr[j]);
782 }
783 }
784
785 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
786 && !using_ktls
787 && s->enc_write_ctx != NULL
788 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
789 || type != SSL3_RT_ALERT)) {
790 size_t rlen, max_send_fragment;
791
792 if (!WPACKET_put_bytes_u8(thispkt, type)) {
793 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
794 goto err;
795 }
796 SSL3_RECORD_add_length(thiswr, 1);
797
798 /* Add TLS1.3 padding */
799 max_send_fragment = ssl_get_max_send_fragment(s);
800 rlen = SSL3_RECORD_get_length(thiswr);
801 if (rlen < max_send_fragment) {
802 size_t padding = 0;
803 size_t max_padding = max_send_fragment - rlen;
804 if (s->record_padding_cb != NULL) {
805 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
806 } else if (s->block_padding > 0) {
807 size_t mask = s->block_padding - 1;
808 size_t remainder;
809
810 /* optimize for power of 2 */
811 if ((s->block_padding & mask) == 0)
812 remainder = rlen & mask;
813 else
814 remainder = rlen % s->block_padding;
815 /* don't want to add a block of padding if we don't have to */
816 if (remainder == 0)
817 padding = 0;
818 else
819 padding = s->block_padding - remainder;
820 }
821 if (padding > 0) {
822 /* do not allow the record to exceed max plaintext length */
823 if (padding > max_padding)
824 padding = max_padding;
825 if (!WPACKET_memset(thispkt, 0, padding)) {
826 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
827 ERR_R_INTERNAL_ERROR);
828 goto err;
829 }
830 SSL3_RECORD_add_length(thiswr, padding);
831 }
832 }
833 }
834
835 /*
836 * we should still have the output to thiswr->data and the input from
837 * wr->input. Length should be thiswr->length. thiswr->data still points
838 * in the wb->buf
839 */
840
841 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
842 unsigned char *mac;
843
844 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
845 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
846 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
847 goto err;
848 }
849 }
850
851 /*
852 * Reserve some bytes for any growth that may occur during encryption.
853 * This will be at most one cipher block or the tag length if using
854 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
855 */
856 if (!using_ktls) {
857 if (!WPACKET_reserve_bytes(thispkt,
858 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
859 NULL)
860 /*
861 * We also need next the amount of bytes written to this
862 * sub-packet
863 */
864 || !WPACKET_get_length(thispkt, &len)) {
865 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
866 goto err;
867 }
868
869 /* Get a pointer to the start of this record excluding header */
870 recordstart = WPACKET_get_curr(thispkt) - len;
871 SSL3_RECORD_set_data(thiswr, recordstart);
872 SSL3_RECORD_reset_input(thiswr);
873 SSL3_RECORD_set_length(thiswr, len);
874 }
875 }
876
877 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
878 /*
879 * We haven't actually negotiated the version yet, but we're trying to
880 * send early data - so we need to use the tls13enc function.
881 */
882 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
883 if (!ossl_statem_in_error(s)) {
884 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
885 }
886 goto err;
887 }
888 } else {
889 if (!using_ktls) {
890 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
891 mac_size) < 1) {
892 if (!ossl_statem_in_error(s)) {
893 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
894 }
895 goto err;
896 }
897 }
898 }
899
900 for (j = 0; j < numpipes; j++) {
901 size_t origlen;
902
903 thispkt = &pkt[j];
904 thiswr = &wr[j];
905
906 if (using_ktls)
907 goto mac_done;
908
909 /* Allocate bytes for the encryption overhead */
910 if (!WPACKET_get_length(thispkt, &origlen)
911 /* Encryption should never shrink the data! */
912 || origlen > thiswr->length
913 || (thiswr->length > origlen
914 && !WPACKET_allocate_bytes(thispkt,
915 thiswr->length - origlen,
916 NULL))) {
917 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
918 goto err;
919 }
920 if (SSL_WRITE_ETM(s) && mac_size != 0) {
921 unsigned char *mac;
922
923 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
924 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
925 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
926 goto err;
927 }
928 SSL3_RECORD_add_length(thiswr, mac_size);
929 }
930
931 if (!WPACKET_get_length(thispkt, &len)
932 || !WPACKET_close(thispkt)) {
933 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
934 goto err;
935 }
936
937 if (s->msg_callback) {
938 recordstart = WPACKET_get_curr(thispkt) - len
939 - SSL3_RT_HEADER_LENGTH;
940 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
941 SSL3_RT_HEADER_LENGTH, ssl,
942 s->msg_callback_arg);
943
944 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
945 unsigned char ctype = type;
946
947 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
948 &ctype, 1, ssl, s->msg_callback_arg);
949 }
950 }
951
952 if (!WPACKET_finish(thispkt)) {
953 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
954 goto err;
955 }
956
957 /* header is added by the kernel when using offload */
958 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
959
960 if (create_empty_fragment) {
961 /*
962 * we are in a recursive call; just return the length, don't write
963 * out anything here
964 */
965 if (j > 0) {
966 /* We should never be pipelining an empty fragment!! */
967 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
968 goto err;
969 }
970 *written = SSL3_RECORD_get_length(thiswr);
971 return 1;
972 }
973
974 mac_done:
975 /*
976 * we should now have thiswr->data pointing to the encrypted data, which
977 * is thiswr->length long
978 */
979 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
980 * debugging */
981
982 /* now let's set up wb */
983 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
984 prefix_len + SSL3_RECORD_get_length(thiswr));
985 }
986
987 /*
988 * memorize arguments so that ssl3_write_pending can detect bad write
989 * retries later
990 */
991 s->rlayer.wpend_tot = totlen;
992 s->rlayer.wpend_buf = buf;
993 s->rlayer.wpend_type = type;
994 s->rlayer.wpend_ret = totlen;
995
996 /* we now just need to write the buffer */
997 return ssl3_write_pending(s, type, buf, totlen, written);
998 err:
999 for (j = 0; j < wpinited; j++)
1000 WPACKET_cleanup(&pkt[j]);
1001 return -1;
1002 }
1003
1004 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1005 *
1006 * Return values are as per SSL_write()
1007 */
1008 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1009 size_t len, size_t *written)
1010 {
1011 int i;
1012 SSL3_BUFFER *wb = s->rlayer.wbuf;
1013 size_t currbuf = 0;
1014 size_t tmpwrit = 0;
1015
1016 if ((s->rlayer.wpend_tot > len)
1017 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1018 && (s->rlayer.wpend_buf != buf))
1019 || (s->rlayer.wpend_type != type)) {
1020 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1021 return -1;
1022 }
1023
1024 for (;;) {
1025 /* Loop until we find a buffer we haven't written out yet */
1026 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1027 && currbuf < s->rlayer.numwpipes - 1) {
1028 currbuf++;
1029 continue;
1030 }
1031 clear_sys_error();
1032 if (s->wbio != NULL) {
1033 s->rwstate = SSL_WRITING;
1034
1035 /*
1036 * To prevent coalescing of control and data messages,
1037 * such as in buffer_write, we flush the BIO
1038 */
1039 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1040 i = BIO_flush(s->wbio);
1041 if (i <= 0)
1042 return i;
1043 BIO_set_ktls_ctrl_msg(s->wbio, type);
1044 }
1045 i = BIO_write(s->wbio, (char *)
1046 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1047 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1048 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1049 if (i >= 0)
1050 tmpwrit = i;
1051 } else {
1052 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1053 i = -1;
1054 }
1055
1056 /*
1057 * When an empty fragment is sent on a connection using KTLS,
1058 * it is sent as a write of zero bytes. If this zero byte
1059 * write succeeds, i will be 0 rather than a non-zero value.
1060 * Treat i == 0 as success rather than an error for zero byte
1061 * writes to permit this case.
1062 */
1063 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1064 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1065 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1066 if (currbuf + 1 < s->rlayer.numwpipes)
1067 continue;
1068 s->rwstate = SSL_NOTHING;
1069 *written = s->rlayer.wpend_ret;
1070 return 1;
1071 } else if (i <= 0) {
1072 if (SSL_CONNECTION_IS_DTLS(s)) {
1073 /*
1074 * For DTLS, just drop it. That's kind of the whole point in
1075 * using a datagram service
1076 */
1077 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1078 }
1079 return i;
1080 }
1081 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1082 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1083 }
1084 }
1085
1086 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1087 int line)
1088 {
1089 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1090
1091 if (ret == OSSL_RECORD_RETURN_RETRY) {
1092 s->rwstate = SSL_READING;
1093 ret = -1;
1094 } else {
1095 s->rwstate = SSL_NOTHING;
1096 if (ret == OSSL_RECORD_RETURN_EOF) {
1097 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1098 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1099 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1100 } else {
1101 ERR_new();
1102 ERR_set_debug(file, line, 0);
1103 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1104 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1105 }
1106 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1107 ERR_new();
1108 ERR_set_debug(file, line, 0);
1109 ossl_statem_fatal(s, s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl),
1110 SSL_R_RECORD_LAYER_FAILURE, NULL);
1111 }
1112 /*
1113 * The record layer distinguishes the cases of EOF, non-fatal
1114 * err and retry. Upper layers do not.
1115 * If we got a retry or success then *ret is already correct,
1116 * otherwise we need to convert the return value.
1117 */
1118 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1119 ret = 0;
1120 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1121 ret = -1;
1122 }
1123
1124 return ret;
1125 }
1126
1127 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
1128 {
1129 if (rr->rechandle != NULL) {
1130 /* The record layer allocated the buffers for this record */
1131 s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
1132 } else {
1133 /* We allocated the buffers for this record (only happens with DTLS) */
1134 OPENSSL_free(rr->data);
1135 }
1136 s->rlayer.curr_rec++;
1137 }
1138
1139 /*-
1140 * Return up to 'len' payload bytes received in 'type' records.
1141 * 'type' is one of the following:
1142 *
1143 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1144 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1145 * - 0 (during a shutdown, no data has to be returned)
1146 *
1147 * If we don't have stored data to work from, read a SSL/TLS record first
1148 * (possibly multiple records if we still don't have anything to return).
1149 *
1150 * This function must handle any surprises the peer may have for us, such as
1151 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1152 * messages are treated as if they were handshake messages *if* the |recvd_type|
1153 * argument is non NULL.
1154 * Also if record payloads contain fragments too small to process, we store
1155 * them until there is enough for the respective protocol (the record protocol
1156 * may use arbitrary fragmentation and even interleaving):
1157 * Change cipher spec protocol
1158 * just 1 byte needed, no need for keeping anything stored
1159 * Alert protocol
1160 * 2 bytes needed (AlertLevel, AlertDescription)
1161 * Handshake protocol
1162 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1163 * to detect unexpected Client Hello and Hello Request messages
1164 * here, anything else is handled by higher layers
1165 * Application data protocol
1166 * none of our business
1167 */
1168 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1169 size_t len, int peek, size_t *readbytes)
1170 {
1171 int i, j, ret;
1172 size_t n, curr_rec, totalbytes;
1173 TLS_RECORD *rr;
1174 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1175 int is_tls13;
1176 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1177
1178 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1179
1180 if ((type != 0
1181 && (type != SSL3_RT_APPLICATION_DATA)
1182 && (type != SSL3_RT_HANDSHAKE))
1183 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1184 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1185 return -1;
1186 }
1187
1188 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1189 /* (partially) satisfy request from storage */
1190 {
1191 unsigned char *src = s->rlayer.handshake_fragment;
1192 unsigned char *dst = buf;
1193 unsigned int k;
1194
1195 /* peek == 0 */
1196 n = 0;
1197 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1198 *dst++ = *src++;
1199 len--;
1200 s->rlayer.handshake_fragment_len--;
1201 n++;
1202 }
1203 /* move any remaining fragment bytes: */
1204 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1205 s->rlayer.handshake_fragment[k] = *src++;
1206
1207 if (recvd_type != NULL)
1208 *recvd_type = SSL3_RT_HANDSHAKE;
1209
1210 *readbytes = n;
1211 return 1;
1212 }
1213
1214 /*
1215 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1216 */
1217
1218 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1219 /* type == SSL3_RT_APPLICATION_DATA */
1220 i = s->handshake_func(ssl);
1221 /* SSLfatal() already called */
1222 if (i < 0)
1223 return i;
1224 if (i == 0)
1225 return -1;
1226 }
1227 start:
1228 s->rwstate = SSL_NOTHING;
1229
1230 /*-
1231 * For each record 'i' up to |num_recs]
1232 * rr[i].type - is the type of record
1233 * rr[i].data, - data
1234 * rr[i].off, - offset into 'data' for next read
1235 * rr[i].length, - number of bytes.
1236 */
1237 /* get new records if necessary */
1238 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1239 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1240 do {
1241 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1242
1243 ret = HANDLE_RLAYER_RETURN(s,
1244 s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
1245 &rr->rechandle,
1246 &rr->version, &rr->type,
1247 &rr->data, &rr->length,
1248 NULL, NULL));
1249 if (ret <= 0) {
1250 /* SSLfatal() already called if appropriate */
1251 return ret;
1252 }
1253 rr->off = 0;
1254 s->rlayer.num_recs++;
1255 } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
1256 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1257 }
1258 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1259
1260 if (s->rlayer.handshake_fragment_len > 0
1261 && rr->type != SSL3_RT_HANDSHAKE
1262 && SSL_CONNECTION_IS_TLS13(s)) {
1263 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1264 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1265 return -1;
1266 }
1267
1268 /*
1269 * Reset the count of consecutive warning alerts if we've got a non-empty
1270 * record that isn't an alert.
1271 */
1272 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1273 s->rlayer.alert_count = 0;
1274
1275 /* we now have a packet which can be read and processed */
1276
1277 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1278 * reset by ssl3_get_finished */
1279 && (rr->type != SSL3_RT_HANDSHAKE)) {
1280 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1281 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1282 return -1;
1283 }
1284
1285 /*
1286 * If the other end has shut down, throw anything we read away (even in
1287 * 'peek' mode)
1288 */
1289 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1290 s->rlayer.curr_rec++;
1291 s->rwstate = SSL_NOTHING;
1292 return 0;
1293 }
1294
1295 if (type == rr->type
1296 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1297 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1298 && !is_tls13)) {
1299 /*
1300 * SSL3_RT_APPLICATION_DATA or
1301 * SSL3_RT_HANDSHAKE or
1302 * SSL3_RT_CHANGE_CIPHER_SPEC
1303 */
1304 /*
1305 * make sure that we are not getting application data when we are
1306 * doing a handshake for the first time
1307 */
1308 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1309 && s->enc_read_ctx == NULL) {
1310 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1311 return -1;
1312 }
1313
1314 if (type == SSL3_RT_HANDSHAKE
1315 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1316 && s->rlayer.handshake_fragment_len > 0) {
1317 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1318 return -1;
1319 }
1320
1321 if (recvd_type != NULL)
1322 *recvd_type = rr->type;
1323
1324 if (len == 0) {
1325 /*
1326 * Skip a zero length record. This ensures multiple calls to
1327 * SSL_read() with a zero length buffer will eventually cause
1328 * SSL_pending() to report data as being available.
1329 */
1330 if (rr->length == 0)
1331 ssl_release_record(s, rr);
1332
1333 return 0;
1334 }
1335
1336 totalbytes = 0;
1337 curr_rec = s->rlayer.curr_rec;
1338 do {
1339 if (len - totalbytes > rr->length)
1340 n = rr->length;
1341 else
1342 n = len - totalbytes;
1343
1344 memcpy(buf, &(rr->data[rr->off]), n);
1345 buf += n;
1346 if (peek) {
1347 /* Mark any zero length record as consumed CVE-2016-6305 */
1348 if (rr->length == 0)
1349 ssl_release_record(s, rr);
1350 } else {
1351 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1352 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1353 rr->length -= n;
1354 rr->off += n;
1355 if (rr->length == 0)
1356 ssl_release_record(s, rr);
1357 }
1358 if (rr->length == 0
1359 || (peek && n == rr->length)) {
1360 rr++;
1361 curr_rec++;
1362 }
1363 totalbytes += n;
1364 } while (type == SSL3_RT_APPLICATION_DATA
1365 && curr_rec < s->rlayer.num_recs
1366 && totalbytes < len);
1367 if (totalbytes == 0) {
1368 /* We must have read empty records. Get more data */
1369 goto start;
1370 }
1371 *readbytes = totalbytes;
1372 return 1;
1373 }
1374
1375 /*
1376 * If we get here, then type != rr->type; if we have a handshake message,
1377 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1378 * were actually expecting a CCS).
1379 */
1380
1381 /*
1382 * Lets just double check that we've not got an SSLv2 record
1383 */
1384 if (rr->version == SSL2_VERSION) {
1385 /*
1386 * Should never happen. ssl3_get_record() should only give us an SSLv2
1387 * record back if this is the first packet and we are looking for an
1388 * initial ClientHello. Therefore |type| should always be equal to
1389 * |rr->type|. If not then something has gone horribly wrong
1390 */
1391 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1392 return -1;
1393 }
1394
1395 if (ssl->method->version == TLS_ANY_VERSION
1396 && (s->server || rr->type != SSL3_RT_ALERT)) {
1397 /*
1398 * If we've got this far and still haven't decided on what version
1399 * we're using then this must be a client side alert we're dealing
1400 * with. We shouldn't be receiving anything other than a ClientHello
1401 * if we are a server.
1402 */
1403 s->version = rr->version;
1404 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1405 return -1;
1406 }
1407
1408 /*-
1409 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1410 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1411 */
1412
1413 if (rr->type == SSL3_RT_ALERT) {
1414 unsigned int alert_level, alert_descr;
1415 unsigned char *alert_bytes = rr->data
1416 + rr->off;
1417 PACKET alert;
1418
1419 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1420 || !PACKET_get_1(&alert, &alert_level)
1421 || !PACKET_get_1(&alert, &alert_descr)
1422 || PACKET_remaining(&alert) != 0) {
1423 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1424 return -1;
1425 }
1426
1427 if (s->msg_callback)
1428 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1429 s->msg_callback_arg);
1430
1431 if (s->info_callback != NULL)
1432 cb = s->info_callback;
1433 else if (ssl->ctx->info_callback != NULL)
1434 cb = ssl->ctx->info_callback;
1435
1436 if (cb != NULL) {
1437 j = (alert_level << 8) | alert_descr;
1438 cb(ssl, SSL_CB_READ_ALERT, j);
1439 }
1440
1441 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1442 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1443 s->s3.warn_alert = alert_descr;
1444 ssl_release_record(s, rr);
1445
1446 s->rlayer.alert_count++;
1447 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1448 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1449 SSL_R_TOO_MANY_WARN_ALERTS);
1450 return -1;
1451 }
1452 }
1453
1454 /*
1455 * Apart from close_notify the only other warning alert in TLSv1.3
1456 * is user_cancelled - which we just ignore.
1457 */
1458 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1459 goto start;
1460 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1461 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1462 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1463 return 0;
1464 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1465 s->rwstate = SSL_NOTHING;
1466 s->s3.fatal_alert = alert_descr;
1467 SSLfatal_data(s, SSL_AD_NO_ALERT,
1468 SSL_AD_REASON_OFFSET + alert_descr,
1469 "SSL alert number %d", alert_descr);
1470 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1471 ssl_release_record(s, rr);
1472 SSL_CTX_remove_session(s->session_ctx, s->session);
1473 return 0;
1474 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1475 /*
1476 * This is a warning but we receive it if we requested
1477 * renegotiation and the peer denied it. Terminate with a fatal
1478 * alert because if application tried to renegotiate it
1479 * presumably had a good reason and expects it to succeed. In
1480 * future we might have a renegotiation where we don't care if
1481 * the peer refused it where we carry on.
1482 */
1483 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1484 return -1;
1485 } else if (alert_level == SSL3_AL_WARNING) {
1486 /* We ignore any other warning alert in TLSv1.2 and below */
1487 goto start;
1488 }
1489
1490 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1491 return -1;
1492 }
1493
1494 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1495 if (rr->type == SSL3_RT_HANDSHAKE) {
1496 BIO *rbio;
1497
1498 /*
1499 * We ignore any handshake messages sent to us unless they are
1500 * TLSv1.3 in which case we want to process them. For all other
1501 * handshake messages we can't do anything reasonable with them
1502 * because we are unable to write any response due to having already
1503 * sent close_notify.
1504 */
1505 if (!SSL_CONNECTION_IS_TLS13(s)) {
1506 ssl_release_record(s, rr);
1507
1508 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1509 goto start;
1510
1511 s->rwstate = SSL_READING;
1512 rbio = SSL_get_rbio(ssl);
1513 BIO_clear_retry_flags(rbio);
1514 BIO_set_retry_read(rbio);
1515 return -1;
1516 }
1517 } else {
1518 /*
1519 * The peer is continuing to send application data, but we have
1520 * already sent close_notify. If this was expected we should have
1521 * been called via SSL_read() and this would have been handled
1522 * above.
1523 * No alert sent because we already sent close_notify
1524 */
1525 ssl_release_record(s, rr);
1526 SSLfatal(s, SSL_AD_NO_ALERT,
1527 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1528 return -1;
1529 }
1530 }
1531
1532 /*
1533 * For handshake data we have 'fragment' storage, so fill that so that we
1534 * can process the header at a fixed place. This is done after the
1535 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1536 * that we're just going to discard.
1537 */
1538 if (rr->type == SSL3_RT_HANDSHAKE) {
1539 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1540 unsigned char *dest = s->rlayer.handshake_fragment;
1541 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1542
1543 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1544 if (rr->length < n)
1545 n = rr->length; /* available bytes */
1546
1547 /* now move 'n' bytes: */
1548 memcpy(dest + *dest_len, rr->data + rr->off, n);
1549 rr->off += n;
1550 rr->length -= n;
1551 *dest_len += n;
1552 if (rr->length == 0)
1553 ssl_release_record(s, rr);
1554
1555 if (*dest_len < dest_maxlen)
1556 goto start; /* fragment was too small */
1557 }
1558
1559 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1560 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1561 return -1;
1562 }
1563
1564 /*
1565 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1566 * protocol violation)
1567 */
1568 if ((s->rlayer.handshake_fragment_len >= 4)
1569 && !ossl_statem_get_in_handshake(s)) {
1570 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1571
1572 /* We found handshake data, so we're going back into init */
1573 ossl_statem_set_in_init(s, 1);
1574
1575 i = s->handshake_func(ssl);
1576 /* SSLfatal() already called if appropriate */
1577 if (i < 0)
1578 return i;
1579 if (i == 0) {
1580 return -1;
1581 }
1582
1583 /*
1584 * If we were actually trying to read early data and we found a
1585 * handshake message, then we don't want to continue to try and read
1586 * the application data any more. It won't be "early" now.
1587 */
1588 if (ined)
1589 return -1;
1590
1591 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1592 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1593 BIO *bio;
1594 /*
1595 * In the case where we try to read application data, but we
1596 * trigger an SSL handshake, we return -1 with the retry
1597 * option set. Otherwise renegotiation may cause nasty
1598 * problems in the blocking world
1599 */
1600 s->rwstate = SSL_READING;
1601 bio = SSL_get_rbio(ssl);
1602 BIO_clear_retry_flags(bio);
1603 BIO_set_retry_read(bio);
1604 return -1;
1605 }
1606 }
1607 goto start;
1608 }
1609
1610 switch (rr->type) {
1611 default:
1612 /*
1613 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1614 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1615 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1616 * no progress is being made and the peer continually sends unrecognised
1617 * record types, using up resources processing them.
1618 */
1619 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1620 return -1;
1621 case SSL3_RT_CHANGE_CIPHER_SPEC:
1622 case SSL3_RT_ALERT:
1623 case SSL3_RT_HANDSHAKE:
1624 /*
1625 * we already handled all of these, with the possible exception of
1626 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1627 * that should not happen when type != rr->type
1628 */
1629 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1630 return -1;
1631 case SSL3_RT_APPLICATION_DATA:
1632 /*
1633 * At this point, we were expecting handshake data, but have
1634 * application data. If the library was running inside ssl3_read()
1635 * (i.e. in_read_app_data is set) and it makes sense to read
1636 * application data at this point (session renegotiation not yet
1637 * started), we will indulge it.
1638 */
1639 if (ossl_statem_app_data_allowed(s)) {
1640 s->s3.in_read_app_data = 2;
1641 return -1;
1642 } else if (ossl_statem_skip_early_data(s)) {
1643 /*
1644 * This can happen after a client sends a CH followed by early_data,
1645 * but the server responds with a HelloRetryRequest. The server
1646 * reads the next record from the client expecting to find a
1647 * plaintext ClientHello but gets a record which appears to be
1648 * application data. The trial decrypt "works" because null
1649 * decryption was applied. We just skip it and move on to the next
1650 * record.
1651 */
1652 if (!ossl_early_data_count_ok(s, rr->length,
1653 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1654 /* SSLfatal() already called */
1655 return -1;
1656 }
1657 ssl_release_record(s, rr);
1658 goto start;
1659 } else {
1660 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1661 return -1;
1662 }
1663 }
1664 }
1665
1666 void ssl3_record_sequence_update(unsigned char *seq)
1667 {
1668 int i;
1669
1670 for (i = 7; i >= 0; i--) {
1671 ++seq[i];
1672 if (seq[i] != 0)
1673 break;
1674 }
1675 }
1676
1677 /*
1678 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1679 * format and false otherwise.
1680 */
1681 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1682 {
1683 if (SSL_CONNECTION_IS_DTLS(rl->s))
1684 return 0;
1685 return rl->tlsrecs[0].version == SSL2_VERSION;
1686 }
1687
1688 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1689 static void rlayer_msg_callback_wrapper(int write_p, int version,
1690 int content_type, const void *buf,
1691 size_t len, void *cbarg)
1692 {
1693 SSL_CONNECTION *s = cbarg;
1694 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1695
1696 if (s->msg_callback != NULL)
1697 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1698 s->msg_callback_arg);
1699 }
1700
1701 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1702 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1703 void *other)
1704 {
1705 SSL_CONNECTION *s = cbarg;
1706
1707 return ssl_security(s, op, bits, nid, other);
1708 }
1709
1710 static const OSSL_DISPATCH rlayer_dispatch[] = {
1711 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1712 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1713 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1714 { 0, NULL }
1715 };
1716
1717 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1718 int level)
1719 {
1720
1721 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1722 if (SSL_CONNECTION_IS_DTLS(s))
1723 return &ossl_dtls_record_method;
1724
1725 return &ossl_tls_record_method;
1726 }
1727
1728 #ifndef OPENSSL_NO_KTLS
1729 /* KTLS does not support renegotiation */
1730 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1731 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1732 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1733 return &ossl_ktls_record_method;
1734 #endif
1735
1736 /* Default to the current OSSL_RECORD_METHOD */
1737 return s->rlayer.rrlmethod;
1738 }
1739
1740 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1741 {
1742 #ifndef OPENSSL_NO_KTLS
1743 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1744
1745 if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1746 /* KTLS does not support renegotiation so disallow it */
1747 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1748 }
1749 #endif
1750 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rlayer.rrlmethod->set_first_handshake != NULL)
1751 s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 1);
1752
1753 if (s->max_pipelines != 0 && s->rlayer.rrlmethod->set_max_pipelines != NULL)
1754 s->rlayer.rrlmethod->set_max_pipelines(s->rlayer.rrl, s->max_pipelines);
1755
1756 return 1;
1757 }
1758
1759 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1760 int direction, int level,
1761 unsigned char *key, size_t keylen,
1762 unsigned char *iv, size_t ivlen,
1763 unsigned char *mackey, size_t mackeylen,
1764 const EVP_CIPHER *ciph, size_t taglen,
1765 int mactype, const EVP_MD *md,
1766 const SSL_COMP *comp)
1767 {
1768 OSSL_PARAM options[5], *opts = options;
1769 OSSL_PARAM settings[6], *set = settings;
1770 const OSSL_RECORD_METHOD *origmeth = s->rlayer.rrlmethod;
1771 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1772 const OSSL_RECORD_METHOD *meth;
1773 int use_etm, stream_mac = 0, tlstree = 0;
1774 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1775 int use_early_data = 0;
1776 uint32_t max_early_data;
1777
1778 meth = ssl_select_next_record_layer(s, level);
1779
1780 if (s->rlayer.rrlmethod != NULL && !s->rlayer.rrlmethod->free(s->rlayer.rrl)) {
1781 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1782 return 0;
1783 }
1784
1785 if (meth != NULL)
1786 s->rlayer.rrlmethod = meth;
1787
1788 if (!ossl_assert(s->rlayer.rrlmethod != NULL)) {
1789 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1790 return 0;
1791 }
1792
1793 /* Parameters that *may* be supported by a record layer if passed */
1794 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1795 &s->options);
1796 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1797 &s->mode);
1798 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1799 &s->rlayer.default_read_buf_len);
1800 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1801 &s->rlayer.read_ahead);
1802 *opts = OSSL_PARAM_construct_end();
1803
1804 /* Parameters that *must* be supported by a record layer if passed */
1805 if (direction == OSSL_RECORD_DIRECTION_READ) {
1806 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1807 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1808 stream_mac = 1;
1809
1810 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1811 tlstree = 1;
1812 } else {
1813 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1814 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1815 stream_mac = 1;
1816
1817 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1818 tlstree = 1;
1819 }
1820
1821 if (use_etm)
1822 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1823 &use_etm);
1824
1825 if (stream_mac)
1826 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1827 &stream_mac);
1828
1829 if (tlstree)
1830 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1831 &tlstree);
1832
1833 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1834 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1835
1836 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1837 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1838 &maxfrag);
1839
1840 /*
1841 * The record layer must check the amount of early data sent or received
1842 * using the early keys. A server also needs to worry about rejected early
1843 * data that might arrive when the handshake keys are in force.
1844 */
1845 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1846 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1847 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1848 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1849 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1850 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1851 }
1852 if (use_early_data) {
1853 max_early_data = ossl_get_max_early_data(s);
1854
1855 if (max_early_data != 0)
1856 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1857 &max_early_data);
1858 }
1859
1860 *set = OSSL_PARAM_construct_end();
1861
1862 for (;;) {
1863 int rlret;
1864 BIO *prev = s->rlayer.rrlnext;
1865 unsigned int epoch = 0;;
1866
1867 if (SSL_CONNECTION_IS_DTLS(s)
1868 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1869 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1870
1871 if (SSL_CONNECTION_IS_DTLS(s))
1872 s->rlayer.rrlnext = BIO_new(BIO_s_dgram_mem());
1873 else
1874 s->rlayer.rrlnext = BIO_new(BIO_s_mem());
1875
1876 if (s->rlayer.rrlnext == NULL) {
1877 BIO_free(prev);
1878 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1879 return 0;
1880 }
1881
1882 rlret = s->rlayer.rrlmethod->new_record_layer(sctx->libctx,
1883 sctx->propq,
1884 version, s->server,
1885 direction, level, epoch,
1886 key, keylen, iv, ivlen,
1887 mackey, mackeylen, ciph,
1888 taglen, mactype, md, comp,
1889 prev, s->rbio,
1890 s->rlayer.rrlnext, NULL,
1891 NULL, settings, options,
1892 rlayer_dispatch, s,
1893 &s->rlayer.rrl);
1894 BIO_free(prev);
1895 switch (rlret) {
1896 case OSSL_RECORD_RETURN_FATAL:
1897 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1898 return 0;
1899
1900 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1901 if (s->rlayer.rrlmethod != origmeth && origmeth != NULL) {
1902 /*
1903 * We tried a new record layer method, but it didn't work out,
1904 * so we fallback to the original method and try again
1905 */
1906 s->rlayer.rrlmethod = origmeth;
1907 continue;
1908 }
1909 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1910 return 0;
1911
1912 case OSSL_RECORD_RETURN_SUCCESS:
1913 break;
1914
1915 default:
1916 /* Should not happen */
1917 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1918 return 0;
1919 }
1920 break;
1921 }
1922
1923 return ssl_post_record_layer_select(s);
1924 }