]> git.ipfire.org Git - thirdparty/openssl.git/blob - ssl/record/rec_layer_s3.c
Move some fields out of the SSL object and into the record layer object
[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 /* TODO(RECLAYER): FIX ME */
1372 #if 0
1373 if (!peek && curr_rec == s->rlayer.num_recs
1374 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1375 && SSL3_BUFFER_get_left(rbuf) == 0)
1376 ssl3_release_read_buffer(s);
1377 #endif
1378 *readbytes = totalbytes;
1379 return 1;
1380 }
1381
1382 /*
1383 * If we get here, then type != rr->type; if we have a handshake message,
1384 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1385 * were actually expecting a CCS).
1386 */
1387
1388 /*
1389 * Lets just double check that we've not got an SSLv2 record
1390 */
1391 if (rr->version == SSL2_VERSION) {
1392 /*
1393 * Should never happen. ssl3_get_record() should only give us an SSLv2
1394 * record back if this is the first packet and we are looking for an
1395 * initial ClientHello. Therefore |type| should always be equal to
1396 * |rr->type|. If not then something has gone horribly wrong
1397 */
1398 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1399 return -1;
1400 }
1401
1402 if (ssl->method->version == TLS_ANY_VERSION
1403 && (s->server || rr->type != SSL3_RT_ALERT)) {
1404 /*
1405 * If we've got this far and still haven't decided on what version
1406 * we're using then this must be a client side alert we're dealing
1407 * with. We shouldn't be receiving anything other than a ClientHello
1408 * if we are a server.
1409 */
1410 s->version = rr->version;
1411 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1412 return -1;
1413 }
1414
1415 /*-
1416 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1417 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1418 */
1419
1420 if (rr->type == SSL3_RT_ALERT) {
1421 unsigned int alert_level, alert_descr;
1422 unsigned char *alert_bytes = rr->data
1423 + rr->off;
1424 PACKET alert;
1425
1426 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1427 || !PACKET_get_1(&alert, &alert_level)
1428 || !PACKET_get_1(&alert, &alert_descr)
1429 || PACKET_remaining(&alert) != 0) {
1430 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1431 return -1;
1432 }
1433
1434 if (s->msg_callback)
1435 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1436 s->msg_callback_arg);
1437
1438 if (s->info_callback != NULL)
1439 cb = s->info_callback;
1440 else if (ssl->ctx->info_callback != NULL)
1441 cb = ssl->ctx->info_callback;
1442
1443 if (cb != NULL) {
1444 j = (alert_level << 8) | alert_descr;
1445 cb(ssl, SSL_CB_READ_ALERT, j);
1446 }
1447
1448 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1449 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1450 s->s3.warn_alert = alert_descr;
1451 ssl_release_record(s, rr);
1452
1453 s->rlayer.alert_count++;
1454 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1455 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1456 SSL_R_TOO_MANY_WARN_ALERTS);
1457 return -1;
1458 }
1459 }
1460
1461 /*
1462 * Apart from close_notify the only other warning alert in TLSv1.3
1463 * is user_cancelled - which we just ignore.
1464 */
1465 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1466 goto start;
1467 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1468 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1469 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1470 return 0;
1471 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1472 s->rwstate = SSL_NOTHING;
1473 s->s3.fatal_alert = alert_descr;
1474 SSLfatal_data(s, SSL_AD_NO_ALERT,
1475 SSL_AD_REASON_OFFSET + alert_descr,
1476 "SSL alert number %d", alert_descr);
1477 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1478 ssl_release_record(s, rr);
1479 SSL_CTX_remove_session(s->session_ctx, s->session);
1480 return 0;
1481 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1482 /*
1483 * This is a warning but we receive it if we requested
1484 * renegotiation and the peer denied it. Terminate with a fatal
1485 * alert because if application tried to renegotiate it
1486 * presumably had a good reason and expects it to succeed. In
1487 * future we might have a renegotiation where we don't care if
1488 * the peer refused it where we carry on.
1489 */
1490 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1491 return -1;
1492 } else if (alert_level == SSL3_AL_WARNING) {
1493 /* We ignore any other warning alert in TLSv1.2 and below */
1494 goto start;
1495 }
1496
1497 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1498 return -1;
1499 }
1500
1501 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1502 if (rr->type == SSL3_RT_HANDSHAKE) {
1503 BIO *rbio;
1504
1505 /*
1506 * We ignore any handshake messages sent to us unless they are
1507 * TLSv1.3 in which case we want to process them. For all other
1508 * handshake messages we can't do anything reasonable with them
1509 * because we are unable to write any response due to having already
1510 * sent close_notify.
1511 */
1512 if (!SSL_CONNECTION_IS_TLS13(s)) {
1513 ssl_release_record(s, rr);
1514
1515 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1516 goto start;
1517
1518 s->rwstate = SSL_READING;
1519 rbio = SSL_get_rbio(ssl);
1520 BIO_clear_retry_flags(rbio);
1521 BIO_set_retry_read(rbio);
1522 return -1;
1523 }
1524 } else {
1525 /*
1526 * The peer is continuing to send application data, but we have
1527 * already sent close_notify. If this was expected we should have
1528 * been called via SSL_read() and this would have been handled
1529 * above.
1530 * No alert sent because we already sent close_notify
1531 */
1532 ssl_release_record(s, rr);
1533 SSLfatal(s, SSL_AD_NO_ALERT,
1534 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1535 return -1;
1536 }
1537 }
1538
1539 /*
1540 * For handshake data we have 'fragment' storage, so fill that so that we
1541 * can process the header at a fixed place. This is done after the
1542 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1543 * that we're just going to discard.
1544 */
1545 if (rr->type == SSL3_RT_HANDSHAKE) {
1546 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1547 unsigned char *dest = s->rlayer.handshake_fragment;
1548 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1549
1550 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1551 if (rr->length < n)
1552 n = rr->length; /* available bytes */
1553
1554 /* now move 'n' bytes: */
1555 memcpy(dest + *dest_len, rr->data + rr->off, n);
1556 rr->off += n;
1557 rr->length -= n;
1558 *dest_len += n;
1559 if (rr->length == 0)
1560 ssl_release_record(s, rr);
1561
1562 if (*dest_len < dest_maxlen)
1563 goto start; /* fragment was too small */
1564 }
1565
1566 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1567 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1568 return -1;
1569 }
1570
1571 /*
1572 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1573 * protocol violation)
1574 */
1575 if ((s->rlayer.handshake_fragment_len >= 4)
1576 && !ossl_statem_get_in_handshake(s)) {
1577 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1578
1579 /* We found handshake data, so we're going back into init */
1580 ossl_statem_set_in_init(s, 1);
1581
1582 i = s->handshake_func(ssl);
1583 /* SSLfatal() already called if appropriate */
1584 if (i < 0)
1585 return i;
1586 if (i == 0) {
1587 return -1;
1588 }
1589
1590 /*
1591 * If we were actually trying to read early data and we found a
1592 * handshake message, then we don't want to continue to try and read
1593 * the application data any more. It won't be "early" now.
1594 */
1595 if (ined)
1596 return -1;
1597
1598 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1599 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1600 BIO *bio;
1601 /*
1602 * In the case where we try to read application data, but we
1603 * trigger an SSL handshake, we return -1 with the retry
1604 * option set. Otherwise renegotiation may cause nasty
1605 * problems in the blocking world
1606 */
1607 s->rwstate = SSL_READING;
1608 bio = SSL_get_rbio(ssl);
1609 BIO_clear_retry_flags(bio);
1610 BIO_set_retry_read(bio);
1611 return -1;
1612 }
1613 }
1614 goto start;
1615 }
1616
1617 switch (rr->type) {
1618 default:
1619 /*
1620 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1621 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1622 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1623 * no progress is being made and the peer continually sends unrecognised
1624 * record types, using up resources processing them.
1625 */
1626 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1627 return -1;
1628 case SSL3_RT_CHANGE_CIPHER_SPEC:
1629 case SSL3_RT_ALERT:
1630 case SSL3_RT_HANDSHAKE:
1631 /*
1632 * we already handled all of these, with the possible exception of
1633 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1634 * that should not happen when type != rr->type
1635 */
1636 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1637 return -1;
1638 case SSL3_RT_APPLICATION_DATA:
1639 /*
1640 * At this point, we were expecting handshake data, but have
1641 * application data. If the library was running inside ssl3_read()
1642 * (i.e. in_read_app_data is set) and it makes sense to read
1643 * application data at this point (session renegotiation not yet
1644 * started), we will indulge it.
1645 */
1646 if (ossl_statem_app_data_allowed(s)) {
1647 s->s3.in_read_app_data = 2;
1648 return -1;
1649 } else if (ossl_statem_skip_early_data(s)) {
1650 /*
1651 * This can happen after a client sends a CH followed by early_data,
1652 * but the server responds with a HelloRetryRequest. The server
1653 * reads the next record from the client expecting to find a
1654 * plaintext ClientHello but gets a record which appears to be
1655 * application data. The trial decrypt "works" because null
1656 * decryption was applied. We just skip it and move on to the next
1657 * record.
1658 */
1659 if (!ossl_early_data_count_ok(s, rr->length,
1660 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1661 /* SSLfatal() already called */
1662 return -1;
1663 }
1664 ssl_release_record(s, rr);
1665 goto start;
1666 } else {
1667 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1668 return -1;
1669 }
1670 }
1671 }
1672
1673 void ssl3_record_sequence_update(unsigned char *seq)
1674 {
1675 int i;
1676
1677 for (i = 7; i >= 0; i--) {
1678 ++seq[i];
1679 if (seq[i] != 0)
1680 break;
1681 }
1682 }
1683
1684 /*
1685 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1686 * format and false otherwise.
1687 */
1688 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1689 {
1690 if (SSL_CONNECTION_IS_DTLS(rl->s))
1691 return 0;
1692 return rl->tlsrecs[0].version == SSL2_VERSION;
1693 }
1694
1695 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1696 static void rlayer_msg_callback_wrapper(int write_p, int version,
1697 int content_type, const void *buf,
1698 size_t len, void *cbarg)
1699 {
1700 SSL_CONNECTION *s = cbarg;
1701 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1702
1703 if (s->msg_callback != NULL)
1704 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1705 s->msg_callback_arg);
1706 }
1707
1708 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1709 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1710 void *other)
1711 {
1712 SSL_CONNECTION *s = cbarg;
1713
1714 return ssl_security(s, op, bits, nid, other);
1715 }
1716
1717 static const OSSL_DISPATCH rlayer_dispatch[] = {
1718 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1719 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1720 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1721 { 0, NULL }
1722 };
1723
1724 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1725 int level)
1726 {
1727
1728 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1729 if (SSL_CONNECTION_IS_DTLS(s))
1730 return &ossl_dtls_record_method;
1731
1732 return &ossl_tls_record_method;
1733 }
1734
1735 #ifndef OPENSSL_NO_KTLS
1736 /* KTLS does not support renegotiation */
1737 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1738 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1739 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1740 return &ossl_ktls_record_method;
1741 #endif
1742
1743 /* Default to the current OSSL_RECORD_METHOD */
1744 return s->rlayer.rrlmethod;
1745 }
1746
1747 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1748 {
1749 #ifndef OPENSSL_NO_KTLS
1750 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1751
1752 if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1753 /* KTLS does not support renegotiation so disallow it */
1754 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1755 }
1756 #endif
1757 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rlayer.rrlmethod->set_first_handshake != NULL)
1758 s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 1);
1759
1760 if (s->max_pipelines != 0 && s->rlayer.rrlmethod->set_max_pipelines != NULL)
1761 s->rlayer.rrlmethod->set_max_pipelines(s->rlayer.rrl, s->max_pipelines);
1762
1763 return 1;
1764 }
1765
1766 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1767 int direction, int level,
1768 unsigned char *key, size_t keylen,
1769 unsigned char *iv, size_t ivlen,
1770 unsigned char *mackey, size_t mackeylen,
1771 const EVP_CIPHER *ciph, size_t taglen,
1772 int mactype, const EVP_MD *md,
1773 const SSL_COMP *comp)
1774 {
1775 OSSL_PARAM options[5], *opts = options;
1776 OSSL_PARAM settings[6], *set = settings;
1777 const OSSL_RECORD_METHOD *origmeth = s->rlayer.rrlmethod;
1778 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1779 const OSSL_RECORD_METHOD *meth;
1780 int use_etm, stream_mac = 0, tlstree = 0;
1781 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1782 int use_early_data = 0;
1783 uint32_t max_early_data;
1784
1785 meth = ssl_select_next_record_layer(s, level);
1786
1787 if (s->rlayer.rrlmethod != NULL && !s->rlayer.rrlmethod->free(s->rlayer.rrl)) {
1788 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1789 return 0;
1790 }
1791
1792 if (meth != NULL)
1793 s->rlayer.rrlmethod = meth;
1794
1795 if (!ossl_assert(s->rlayer.rrlmethod != NULL)) {
1796 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1797 return 0;
1798 }
1799
1800 /* Parameters that *may* be supported by a record layer if passed */
1801 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1802 &s->options);
1803 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1804 &s->mode);
1805 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1806 &s->rlayer.default_read_buf_len);
1807 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1808 &s->rlayer.read_ahead);
1809 *opts = OSSL_PARAM_construct_end();
1810
1811 /* Parameters that *must* be supported by a record layer if passed */
1812 if (direction == OSSL_RECORD_DIRECTION_READ) {
1813 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1814 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1815 stream_mac = 1;
1816
1817 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1818 tlstree = 1;
1819 } else {
1820 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1821 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1822 stream_mac = 1;
1823
1824 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1825 tlstree = 1;
1826 }
1827
1828 if (use_etm)
1829 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1830 &use_etm);
1831
1832 if (stream_mac)
1833 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1834 &stream_mac);
1835
1836 if (tlstree)
1837 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1838 &tlstree);
1839
1840 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1841 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1842
1843 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1844 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1845 &maxfrag);
1846
1847 /*
1848 * The record layer must check the amount of early data sent or received
1849 * using the early keys. A server also needs to worry about rejected early
1850 * data that might arrive when the handshake keys are in force.
1851 */
1852 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1853 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1854 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1855 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1856 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1857 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1858 }
1859 if (use_early_data) {
1860 max_early_data = ossl_get_max_early_data(s);
1861
1862 if (max_early_data != 0)
1863 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1864 &max_early_data);
1865 }
1866
1867 *set = OSSL_PARAM_construct_end();
1868
1869 for (;;) {
1870 int rlret;
1871 BIO *prev = s->rlayer.rrlnext;
1872 unsigned int epoch = 0;;
1873
1874 if (SSL_CONNECTION_IS_DTLS(s)
1875 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1876 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1877
1878 if (SSL_CONNECTION_IS_DTLS(s))
1879 s->rlayer.rrlnext = BIO_new(BIO_s_dgram_mem());
1880 else
1881 s->rlayer.rrlnext = BIO_new(BIO_s_mem());
1882
1883 if (s->rlayer.rrlnext == NULL) {
1884 BIO_free(prev);
1885 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1886 return 0;
1887 }
1888
1889 rlret = s->rlayer.rrlmethod->new_record_layer(sctx->libctx,
1890 sctx->propq,
1891 version, s->server,
1892 direction, level, epoch,
1893 key, keylen, iv, ivlen,
1894 mackey, mackeylen, ciph,
1895 taglen, mactype, md, comp,
1896 prev, s->rbio,
1897 s->rlayer.rrlnext, NULL,
1898 NULL, settings, options,
1899 rlayer_dispatch, s,
1900 &s->rlayer.rrl);
1901 BIO_free(prev);
1902 switch (rlret) {
1903 case OSSL_RECORD_RETURN_FATAL:
1904 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1905 return 0;
1906
1907 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1908 if (s->rlayer.rrlmethod != origmeth && origmeth != NULL) {
1909 /*
1910 * We tried a new record layer method, but it didn't work out,
1911 * so we fallback to the original method and try again
1912 */
1913 s->rlayer.rrlmethod = origmeth;
1914 continue;
1915 }
1916 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1917 return 0;
1918
1919 case OSSL_RECORD_RETURN_SUCCESS:
1920 break;
1921
1922 default:
1923 /* Should not happen */
1924 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1925 return 0;
1926 }
1927 break;
1928 }
1929
1930 return ssl_post_record_layer_select(s);
1931 }