2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
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
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"
21 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
22 !( defined(AES_ASM) && ( \
23 defined(__x86_64) || defined(__x86_64__) || \
24 defined(_M_AMD64) || defined(_M_X64) ) \
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
30 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
35 void RECORD_LAYER_clear(RECORD_LAYER *rl)
38 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
39 rl->handshake_fragment_len = 0;
45 ssl3_release_write_buffer(rl->s);
47 RECORD_LAYER_reset_read_sequence(rl);
48 RECORD_LAYER_reset_write_sequence(rl);
50 if (rl->rrlmethod != NULL)
51 rl->rrlmethod->free(rl->rrl); /* Ignore return value */
52 BIO_free(rl->rrlnext);
57 DTLS_RECORD_LAYER_clear(rl);
60 void RECORD_LAYER_release(RECORD_LAYER *rl)
62 if (rl->numwpipes > 0)
63 ssl3_release_write_buffer(rl->s);
66 /* Checks if we have unprocessed read ahead data pending */
67 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
69 return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
72 /* Checks if we have decrypted unread record data pending */
73 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
75 return (rl->curr_rec < rl->num_recs)
76 || rl->rrlmethod->processed_read_pending(rl->rrl);
79 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
81 return (rl->numwpipes > 0)
82 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
85 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
87 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
90 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
92 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
95 size_t ssl3_pending(const SSL *s)
98 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
103 if (SSL_CONNECTION_IS_DTLS(sc)) {
107 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
108 while ((item = pqueue_next(&iter)) != NULL) {
110 num += rdata->length;
114 for (i = 0; i < sc->rlayer.num_recs; i++) {
115 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
117 num += sc->rlayer.tlsrecs[i].length;
120 num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
125 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
127 ctx->default_read_buf_len = len;
130 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
132 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
136 sc->rlayer.default_read_buf_len = len;
139 const char *SSL_rstate_string_long(const SSL *s)
141 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
147 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
150 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
155 const char *SSL_rstate_string(const SSL *s)
157 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
163 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
166 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
172 * Call this to write data in records of type 'type' It will return <= 0 if
173 * not all data has been sent or non-blocking IO.
175 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
178 const unsigned char *buf = buf_;
180 size_t n, max_send_fragment, split_send_fragment, maxpipes;
181 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
187 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
192 wb = &s->rlayer.wbuf[0];
193 s->rwstate = SSL_NOTHING;
194 tot = s->rlayer.wnum;
196 * ensure that if we end up with a smaller value of data to write out
197 * than the original len from a write which didn't complete for
198 * non-blocking I/O and also somehow ended up avoiding the check for
199 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
200 * possible to end up with (len-tot) as a large number that will then
201 * promptly send beyond the end of the users buffer ... so we trap and
202 * report the error in a way the user will notice
204 if ((len < s->rlayer.wnum)
205 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
206 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
210 if (s->early_data_state == SSL_EARLY_DATA_WRITING
211 && !ossl_early_data_count_ok(s, len, 0, 1)) {
212 /* SSLfatal() already called */
219 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
220 * into init unless we have writes pending - in which case we should finish
223 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
224 || s->ext.extra_tickets_expected > 0))
225 ossl_statem_set_in_init(s, 1);
228 * When writing early data on the server side we could be "in_init" in
229 * between receiving the EoED and the CF - but we don't want to handle those
232 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
233 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
234 i = s->handshake_func(ssl);
235 /* SSLfatal() already called */
244 * first check if there is a SSL3_BUFFER still being written out. This
245 * will happen with non blocking IO
248 /* SSLfatal() already called if appropriate */
249 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
252 /* XXX should we ssl3_release_write_buffer if i<0? */
253 s->rlayer.wnum = tot;
256 tot += tmpwrit; /* this might be last fragment */
258 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
260 * Depending on platform multi-block can deliver several *times*
261 * better performance. Downside is that it has to allocate
262 * jumbo buffer to accommodate up to 8 records, but the
263 * compromise is considered worthy.
265 if (type == SSL3_RT_APPLICATION_DATA
266 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
267 && s->compress == NULL
268 && s->msg_callback == NULL
270 && SSL_USE_EXPLICIT_IV(s)
271 && !BIO_get_ktls_send(s->wbio)
272 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
273 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
274 unsigned char aad[13];
275 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
279 /* minimize address aliasing conflicts */
280 if ((max_send_fragment & 0xfff) == 0)
281 max_send_fragment -= 512;
283 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
284 ssl3_release_write_buffer(s);
286 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
287 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
288 (int)max_send_fragment, NULL);
290 if (len >= 8 * max_send_fragment)
295 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
296 /* SSLfatal() already called */
299 } else if (tot == len) { /* done? */
300 /* free jumbo buffer */
301 ssl3_release_write_buffer(s);
308 if (n < 4 * max_send_fragment) {
309 /* free jumbo buffer */
310 ssl3_release_write_buffer(s);
314 if (s->s3.alert_dispatch) {
315 i = ssl->method->ssl_dispatch_alert(ssl);
317 /* SSLfatal() already called if appropriate */
318 s->rlayer.wnum = tot;
323 if (n >= 8 * max_send_fragment)
324 nw = max_send_fragment * (mb_param.interleave = 8);
326 nw = max_send_fragment * (mb_param.interleave = 4);
328 memcpy(aad, s->rlayer.write_sequence, 8);
330 aad[9] = (unsigned char)(s->version >> 8);
331 aad[10] = (unsigned char)(s->version);
338 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
339 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
340 sizeof(mb_param), &mb_param);
341 packlen = (size_t)packleni;
342 if (packleni <= 0 || packlen > wb->len) { /* never happens */
343 /* free jumbo buffer */
344 ssl3_release_write_buffer(s);
348 mb_param.out = wb->buf;
349 mb_param.inp = &buf[tot];
352 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
353 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
354 sizeof(mb_param), &mb_param) <= 0)
357 s->rlayer.write_sequence[7] += mb_param.interleave;
358 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
360 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
366 s->rlayer.wpend_tot = nw;
367 s->rlayer.wpend_buf = &buf[tot];
368 s->rlayer.wpend_type = type;
369 s->rlayer.wpend_ret = nw;
371 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
373 /* SSLfatal() already called if appropriate */
374 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
375 /* free jumbo buffer */
376 ssl3_release_write_buffer(s);
378 s->rlayer.wnum = tot;
382 /* free jumbo buffer */
383 ssl3_release_write_buffer(s);
384 *written = tot + tmpwrit;
391 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
392 if (tot == len) { /* done? */
393 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
394 ssl3_release_write_buffer(s);
402 max_send_fragment = ssl_get_max_send_fragment(s);
403 split_send_fragment = ssl_get_split_send_fragment(s);
405 * If max_pipelines is 0 then this means "undefined" and we default to
406 * 1 pipeline. Similarly if the cipher does not support pipelined
407 * processing then we also only use 1 pipeline, or if we're not using
410 maxpipes = s->max_pipelines;
411 if (maxpipes > SSL_MAX_PIPELINES) {
413 * We should have prevented this when we set max_pipelines so we
416 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
420 || s->enc_write_ctx == NULL
421 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
422 & EVP_CIPH_FLAG_PIPELINE) == 0
423 || !SSL_USE_EXPLICIT_IV(s))
425 if (max_send_fragment == 0
426 || split_send_fragment == 0
427 || split_send_fragment > max_send_fragment) {
429 * We should have prevented this when we set/get the split and max send
430 * fragments so we shouldn't get here
432 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
437 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
443 numpipes = ((n - 1) / split_send_fragment) + 1;
444 if (numpipes > maxpipes)
447 if (n / numpipes >= max_send_fragment) {
449 * We have enough data to completely fill all available
452 for (j = 0; j < numpipes; j++) {
453 pipelens[j] = max_send_fragment;
456 /* We can partially fill all available pipelines */
457 tmppipelen = n / numpipes;
458 remain = n % numpipes;
459 for (j = 0; j < numpipes; j++) {
460 pipelens[j] = tmppipelen;
466 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
469 /* SSLfatal() already called if appropriate */
470 /* XXX should we ssl3_release_write_buffer if i<0? */
471 s->rlayer.wnum = tot;
476 (type == SSL3_RT_APPLICATION_DATA &&
477 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
479 * next chunk of data should get another prepended empty fragment
480 * in ciphersuites with known-IV weakness:
482 s->s3.empty_fragment_done = 0;
485 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
486 && !SSL_CONNECTION_IS_DTLS(s))
487 ssl3_release_write_buffer(s);
489 *written = tot + tmpwrit;
498 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
499 size_t *pipelens, size_t numpipes,
500 int create_empty_fragment, size_t *written)
502 WPACKET pkt[SSL_MAX_PIPELINES];
503 SSL3_RECORD wr[SSL_MAX_PIPELINES];
506 unsigned char *recordstart;
507 int i, mac_size, clear = 0;
508 size_t prefix_len = 0;
513 size_t totlen = 0, len, wpinited = 0;
516 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
518 for (j = 0; j < numpipes; j++)
519 totlen += pipelens[j];
521 * first check if there is a SSL3_BUFFER still being written out. This
522 * will happen with non blocking IO
524 if (RECORD_LAYER_write_pending(&s->rlayer)) {
525 /* Calls SSLfatal() as required */
526 return ssl3_write_pending(s, type, buf, totlen, written);
529 /* If we have an alert to send, lets send it */
530 if (s->s3.alert_dispatch) {
531 i = ssl->method->ssl_dispatch_alert(ssl);
533 /* SSLfatal() already called if appropriate */
536 /* if it went, fall through and send more stuff */
539 if (s->rlayer.numwpipes < numpipes) {
540 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
541 /* SSLfatal() already called */
546 if (totlen == 0 && !create_empty_fragment)
552 || (s->enc_write_ctx == NULL)
553 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
554 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
557 mac_size = EVP_MD_CTX_get_size(s->write_hash);
559 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
565 * 'create_empty_fragment' is true only when this function calls itself
567 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
569 * countermeasure against known-IV weakness in CBC ciphersuites (see
570 * http://www.openssl.org/~bodo/tls-cbc.txt)
573 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
575 * recursive function call with 'create_empty_fragment' set; this
576 * prepares and buffers the data for an empty fragment (these
577 * 'prefix_len' bytes are sent out later together with the actual
580 size_t tmppipelen = 0;
583 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
585 /* SSLfatal() already called if appropriate */
590 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
591 /* insufficient space */
592 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
597 s->s3.empty_fragment_done = 1;
600 using_ktls = BIO_get_ktls_send(s->wbio);
603 * ktls doesn't modify the buffer, but to avoid a warning we need to
604 * discard the const qualifier.
605 * This doesn't leak memory because the buffers have been released when
608 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
609 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
610 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
611 goto wpacket_init_complete;
614 if (create_empty_fragment) {
615 wb = &s->rlayer.wbuf[0];
616 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
618 * extra fragment would be couple of cipher blocks, which would be
619 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
620 * payload, then we can just pretend we simply have two headers.
622 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
623 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
625 SSL3_BUFFER_set_offset(wb, align);
626 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
627 SSL3_BUFFER_get_len(wb), 0)
628 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
629 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
633 } else if (prefix_len) {
634 wb = &s->rlayer.wbuf[0];
635 if (!WPACKET_init_static_len(&pkt[0],
636 SSL3_BUFFER_get_buf(wb),
637 SSL3_BUFFER_get_len(wb), 0)
638 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
639 + prefix_len, NULL)) {
640 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
645 for (j = 0; j < numpipes; j++) {
648 wb = &s->rlayer.wbuf[j];
649 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
650 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
651 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
653 SSL3_BUFFER_set_offset(wb, align);
654 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
655 SSL3_BUFFER_get_len(wb), 0)
656 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
657 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
664 /* Explicit IV length, block ciphers appropriate version flag */
665 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
666 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
667 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
668 if (mode == EVP_CIPH_CBC_MODE) {
669 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
671 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
676 } else if (mode == EVP_CIPH_GCM_MODE) {
677 /* Need explicit part of IV for GCM mode */
678 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
679 } else if (mode == EVP_CIPH_CCM_MODE) {
680 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
684 wpacket_init_complete:
687 /* Clear our SSL3_RECORD structures */
688 memset(wr, 0, sizeof(wr));
689 for (j = 0; j < numpipes; j++) {
690 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
692 unsigned char *compressdata = NULL;
694 unsigned int rectype;
700 * In TLSv1.3, once encrypting, we always use application data for the
703 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
704 && s->enc_write_ctx != NULL
705 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
706 || type != SSL3_RT_ALERT))
707 rectype = SSL3_RT_APPLICATION_DATA;
710 SSL3_RECORD_set_type(thiswr, rectype);
713 * Some servers hang if initial client hello is larger than 256 bytes
714 * and record version number > TLS 1.0
716 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
718 && TLS1_get_version(ssl) > TLS1_VERSION
719 && s->hello_retry_request == SSL_HRR_NONE)
720 version = TLS1_VERSION;
721 SSL3_RECORD_set_rec_version(thiswr, version);
723 maxcomplen = pipelens[j];
724 if (s->compress != NULL)
725 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
728 * When using offload kernel will write the header.
729 * Otherwise write the header now
732 && (!WPACKET_put_bytes_u8(thispkt, rectype)
733 || !WPACKET_put_bytes_u16(thispkt, version)
734 || !WPACKET_start_sub_packet_u16(thispkt)
736 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
738 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
740 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
744 /* lets setup the record stuff. */
745 SSL3_RECORD_set_data(thiswr, compressdata);
746 SSL3_RECORD_set_length(thiswr, pipelens[j]);
747 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
748 totlen += pipelens[j];
751 * we now 'read' from thiswr->input, thiswr->length bytes into
755 /* first we compress */
756 if (s->compress != NULL) {
757 if (!ssl3_do_compress(s, thiswr)
758 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
759 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
764 SSL3_RECORD_reset_data(&wr[j]);
766 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
767 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
770 SSL3_RECORD_reset_input(&wr[j]);
774 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
776 && s->enc_write_ctx != NULL
777 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
778 || type != SSL3_RT_ALERT)) {
779 size_t rlen, max_send_fragment;
781 if (!WPACKET_put_bytes_u8(thispkt, type)) {
782 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
785 SSL3_RECORD_add_length(thiswr, 1);
787 /* Add TLS1.3 padding */
788 max_send_fragment = ssl_get_max_send_fragment(s);
789 rlen = SSL3_RECORD_get_length(thiswr);
790 if (rlen < max_send_fragment) {
792 size_t max_padding = max_send_fragment - rlen;
793 if (s->record_padding_cb != NULL) {
794 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
795 } else if (s->block_padding > 0) {
796 size_t mask = s->block_padding - 1;
799 /* optimize for power of 2 */
800 if ((s->block_padding & mask) == 0)
801 remainder = rlen & mask;
803 remainder = rlen % s->block_padding;
804 /* don't want to add a block of padding if we don't have to */
808 padding = s->block_padding - remainder;
811 /* do not allow the record to exceed max plaintext length */
812 if (padding > max_padding)
813 padding = max_padding;
814 if (!WPACKET_memset(thispkt, 0, padding)) {
815 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
816 ERR_R_INTERNAL_ERROR);
819 SSL3_RECORD_add_length(thiswr, padding);
825 * we should still have the output to thiswr->data and the input from
826 * wr->input. Length should be thiswr->length. thiswr->data still points
830 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
833 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
834 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
835 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
841 * Reserve some bytes for any growth that may occur during encryption.
842 * This will be at most one cipher block or the tag length if using
843 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
846 if (!WPACKET_reserve_bytes(thispkt,
847 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
850 * We also need next the amount of bytes written to this
853 || !WPACKET_get_length(thispkt, &len)) {
854 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
858 /* Get a pointer to the start of this record excluding header */
859 recordstart = WPACKET_get_curr(thispkt) - len;
860 SSL3_RECORD_set_data(thiswr, recordstart);
861 SSL3_RECORD_reset_input(thiswr);
862 SSL3_RECORD_set_length(thiswr, len);
866 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
868 * We haven't actually negotiated the version yet, but we're trying to
869 * send early data - so we need to use the tls13enc function.
871 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
872 if (!ossl_statem_in_error(s)) {
873 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
879 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
881 if (!ossl_statem_in_error(s)) {
882 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
889 for (j = 0; j < numpipes; j++) {
898 /* Allocate bytes for the encryption overhead */
899 if (!WPACKET_get_length(thispkt, &origlen)
900 /* Encryption should never shrink the data! */
901 || origlen > thiswr->length
902 || (thiswr->length > origlen
903 && !WPACKET_allocate_bytes(thispkt,
904 thiswr->length - origlen,
906 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
909 if (SSL_WRITE_ETM(s) && mac_size != 0) {
912 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
913 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
914 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
917 SSL3_RECORD_add_length(thiswr, mac_size);
920 if (!WPACKET_get_length(thispkt, &len)
921 || !WPACKET_close(thispkt)) {
922 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
926 if (s->msg_callback) {
927 recordstart = WPACKET_get_curr(thispkt) - len
928 - SSL3_RT_HEADER_LENGTH;
929 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
930 SSL3_RT_HEADER_LENGTH, ssl,
931 s->msg_callback_arg);
933 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
934 unsigned char ctype = type;
936 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
937 &ctype, 1, ssl, s->msg_callback_arg);
941 if (!WPACKET_finish(thispkt)) {
942 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
946 /* header is added by the kernel when using offload */
947 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
949 if (create_empty_fragment) {
951 * we are in a recursive call; just return the length, don't write
955 /* We should never be pipelining an empty fragment!! */
956 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
959 *written = SSL3_RECORD_get_length(thiswr);
965 * we should now have thiswr->data pointing to the encrypted data, which
966 * is thiswr->length long
968 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
971 /* now let's set up wb */
972 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
973 prefix_len + SSL3_RECORD_get_length(thiswr));
977 * memorize arguments so that ssl3_write_pending can detect bad write
980 s->rlayer.wpend_tot = totlen;
981 s->rlayer.wpend_buf = buf;
982 s->rlayer.wpend_type = type;
983 s->rlayer.wpend_ret = totlen;
985 /* we now just need to write the buffer */
986 return ssl3_write_pending(s, type, buf, totlen, written);
988 for (j = 0; j < wpinited; j++)
989 WPACKET_cleanup(&pkt[j]);
993 /* if SSL3_BUFFER_get_left() != 0, we need to call this
995 * Return values are as per SSL_write()
997 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
998 size_t len, size_t *written)
1001 SSL3_BUFFER *wb = s->rlayer.wbuf;
1005 if ((s->rlayer.wpend_tot > len)
1006 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1007 && (s->rlayer.wpend_buf != buf))
1008 || (s->rlayer.wpend_type != type)) {
1009 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1014 /* Loop until we find a buffer we haven't written out yet */
1015 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1016 && currbuf < s->rlayer.numwpipes - 1) {
1021 if (s->wbio != NULL) {
1022 s->rwstate = SSL_WRITING;
1025 * To prevent coalescing of control and data messages,
1026 * such as in buffer_write, we flush the BIO
1028 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1029 i = BIO_flush(s->wbio);
1032 BIO_set_ktls_ctrl_msg(s->wbio, type);
1034 i = BIO_write(s->wbio, (char *)
1035 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1036 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1037 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1041 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1046 * When an empty fragment is sent on a connection using KTLS,
1047 * it is sent as a write of zero bytes. If this zero byte
1048 * write succeeds, i will be 0 rather than a non-zero value.
1049 * Treat i == 0 as success rather than an error for zero byte
1050 * writes to permit this case.
1052 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1053 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1054 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1055 if (currbuf + 1 < s->rlayer.numwpipes)
1057 s->rwstate = SSL_NOTHING;
1058 *written = s->rlayer.wpend_ret;
1060 } else if (i <= 0) {
1061 if (SSL_CONNECTION_IS_DTLS(s)) {
1063 * For DTLS, just drop it. That's kind of the whole point in
1064 * using a datagram service
1066 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1070 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1071 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1075 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1078 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1080 if (ret == OSSL_RECORD_RETURN_RETRY) {
1081 s->rwstate = SSL_READING;
1084 s->rwstate = SSL_NOTHING;
1085 if (ret == OSSL_RECORD_RETURN_EOF) {
1086 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1087 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1088 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1091 ERR_set_debug(file, line, 0);
1092 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1093 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1095 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1097 ERR_set_debug(file, line, 0);
1098 ossl_statem_fatal(s, s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl),
1099 SSL_R_RECORD_LAYER_FAILURE, NULL);
1102 * The record layer distinguishes the cases of EOF, non-fatal
1103 * err and retry. Upper layers do not.
1104 * If we got a retry or success then *ret is already correct,
1105 * otherwise we need to convert the return value.
1107 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1109 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1116 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
1118 if (rr->rechandle != NULL) {
1119 /* The record layer allocated the buffers for this record */
1120 s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
1122 /* We allocated the buffers for this record (only happens with DTLS) */
1123 OPENSSL_free(rr->data);
1125 s->rlayer.curr_rec++;
1129 * Return up to 'len' payload bytes received in 'type' records.
1130 * 'type' is one of the following:
1132 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1133 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1134 * - 0 (during a shutdown, no data has to be returned)
1136 * If we don't have stored data to work from, read a SSL/TLS record first
1137 * (possibly multiple records if we still don't have anything to return).
1139 * This function must handle any surprises the peer may have for us, such as
1140 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1141 * messages are treated as if they were handshake messages *if* the |recvd_type|
1142 * argument is non NULL.
1143 * Also if record payloads contain fragments too small to process, we store
1144 * them until there is enough for the respective protocol (the record protocol
1145 * may use arbitrary fragmentation and even interleaving):
1146 * Change cipher spec protocol
1147 * just 1 byte needed, no need for keeping anything stored
1149 * 2 bytes needed (AlertLevel, AlertDescription)
1150 * Handshake protocol
1151 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1152 * to detect unexpected Client Hello and Hello Request messages
1153 * here, anything else is handled by higher layers
1154 * Application data protocol
1155 * none of our business
1157 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1158 size_t len, int peek, size_t *readbytes)
1161 size_t n, curr_rec, totalbytes;
1163 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1165 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1167 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1170 && (type != SSL3_RT_APPLICATION_DATA)
1171 && (type != SSL3_RT_HANDSHAKE))
1172 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1173 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1177 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1178 /* (partially) satisfy request from storage */
1180 unsigned char *src = s->rlayer.handshake_fragment;
1181 unsigned char *dst = buf;
1186 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1189 s->rlayer.handshake_fragment_len--;
1192 /* move any remaining fragment bytes: */
1193 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1194 s->rlayer.handshake_fragment[k] = *src++;
1196 if (recvd_type != NULL)
1197 *recvd_type = SSL3_RT_HANDSHAKE;
1204 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1207 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1208 /* type == SSL3_RT_APPLICATION_DATA */
1209 i = s->handshake_func(ssl);
1210 /* SSLfatal() already called */
1217 s->rwstate = SSL_NOTHING;
1220 * For each record 'i' up to |num_recs]
1221 * rr[i].type - is the type of record
1222 * rr[i].data, - data
1223 * rr[i].off, - offset into 'data' for next read
1224 * rr[i].length, - number of bytes.
1226 /* get new records if necessary */
1227 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1228 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1230 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1232 ret = HANDLE_RLAYER_RETURN(s,
1233 s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
1235 &rr->version, &rr->type,
1236 &rr->data, &rr->length,
1239 /* SSLfatal() already called if appropriate */
1243 s->rlayer.num_recs++;
1244 } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
1245 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1247 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1249 if (s->rlayer.handshake_fragment_len > 0
1250 && rr->type != SSL3_RT_HANDSHAKE
1251 && SSL_CONNECTION_IS_TLS13(s)) {
1252 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1253 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1258 * Reset the count of consecutive warning alerts if we've got a non-empty
1259 * record that isn't an alert.
1261 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1262 s->rlayer.alert_count = 0;
1264 /* we now have a packet which can be read and processed */
1266 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1267 * reset by ssl3_get_finished */
1268 && (rr->type != SSL3_RT_HANDSHAKE)) {
1269 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1270 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1275 * If the other end has shut down, throw anything we read away (even in
1278 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1279 s->rlayer.curr_rec++;
1280 s->rwstate = SSL_NOTHING;
1284 if (type == rr->type
1285 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1286 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1289 * SSL3_RT_APPLICATION_DATA or
1290 * SSL3_RT_HANDSHAKE or
1291 * SSL3_RT_CHANGE_CIPHER_SPEC
1294 * make sure that we are not getting application data when we are
1295 * doing a handshake for the first time
1297 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1298 && s->enc_read_ctx == NULL) {
1299 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1303 if (type == SSL3_RT_HANDSHAKE
1304 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1305 && s->rlayer.handshake_fragment_len > 0) {
1306 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1310 if (recvd_type != NULL)
1311 *recvd_type = rr->type;
1315 * Skip a zero length record. This ensures multiple calls to
1316 * SSL_read() with a zero length buffer will eventually cause
1317 * SSL_pending() to report data as being available.
1319 if (rr->length == 0)
1320 ssl_release_record(s, rr);
1326 curr_rec = s->rlayer.curr_rec;
1328 if (len - totalbytes > rr->length)
1331 n = len - totalbytes;
1333 memcpy(buf, &(rr->data[rr->off]), n);
1336 /* Mark any zero length record as consumed CVE-2016-6305 */
1337 if (rr->length == 0)
1338 ssl_release_record(s, rr);
1340 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1341 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1344 if (rr->length == 0)
1345 ssl_release_record(s, rr);
1348 || (peek && n == rr->length)) {
1353 } while (type == SSL3_RT_APPLICATION_DATA
1354 && curr_rec < s->rlayer.num_recs
1355 && totalbytes < len);
1356 if (totalbytes == 0) {
1357 /* We must have read empty records. Get more data */
1360 *readbytes = totalbytes;
1365 * If we get here, then type != rr->type; if we have a handshake message,
1366 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1367 * were actually expecting a CCS).
1371 * Lets just double check that we've not got an SSLv2 record
1373 if (rr->version == SSL2_VERSION) {
1375 * Should never happen. ssl3_get_record() should only give us an SSLv2
1376 * record back if this is the first packet and we are looking for an
1377 * initial ClientHello. Therefore |type| should always be equal to
1378 * |rr->type|. If not then something has gone horribly wrong
1380 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1384 if (ssl->method->version == TLS_ANY_VERSION
1385 && (s->server || rr->type != SSL3_RT_ALERT)) {
1387 * If we've got this far and still haven't decided on what version
1388 * we're using then this must be a client side alert we're dealing
1389 * with. We shouldn't be receiving anything other than a ClientHello
1390 * if we are a server.
1392 s->version = rr->version;
1393 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1398 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1399 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1402 if (rr->type == SSL3_RT_ALERT) {
1403 unsigned int alert_level, alert_descr;
1404 unsigned char *alert_bytes = rr->data
1408 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1409 || !PACKET_get_1(&alert, &alert_level)
1410 || !PACKET_get_1(&alert, &alert_descr)
1411 || PACKET_remaining(&alert) != 0) {
1412 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1416 if (s->msg_callback)
1417 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1418 s->msg_callback_arg);
1420 if (s->info_callback != NULL)
1421 cb = s->info_callback;
1422 else if (ssl->ctx->info_callback != NULL)
1423 cb = ssl->ctx->info_callback;
1426 j = (alert_level << 8) | alert_descr;
1427 cb(ssl, SSL_CB_READ_ALERT, j);
1430 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1431 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1432 s->s3.warn_alert = alert_descr;
1433 ssl_release_record(s, rr);
1435 s->rlayer.alert_count++;
1436 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1437 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1438 SSL_R_TOO_MANY_WARN_ALERTS);
1444 * Apart from close_notify the only other warning alert in TLSv1.3
1445 * is user_cancelled - which we just ignore.
1447 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1449 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1450 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1451 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1453 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1454 s->rwstate = SSL_NOTHING;
1455 s->s3.fatal_alert = alert_descr;
1456 SSLfatal_data(s, SSL_AD_NO_ALERT,
1457 SSL_AD_REASON_OFFSET + alert_descr,
1458 "SSL alert number %d", alert_descr);
1459 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1460 ssl_release_record(s, rr);
1461 SSL_CTX_remove_session(s->session_ctx, s->session);
1463 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1465 * This is a warning but we receive it if we requested
1466 * renegotiation and the peer denied it. Terminate with a fatal
1467 * alert because if application tried to renegotiate it
1468 * presumably had a good reason and expects it to succeed. In
1469 * future we might have a renegotiation where we don't care if
1470 * the peer refused it where we carry on.
1472 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1474 } else if (alert_level == SSL3_AL_WARNING) {
1475 /* We ignore any other warning alert in TLSv1.2 and below */
1479 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1483 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1484 if (rr->type == SSL3_RT_HANDSHAKE) {
1488 * We ignore any handshake messages sent to us unless they are
1489 * TLSv1.3 in which case we want to process them. For all other
1490 * handshake messages we can't do anything reasonable with them
1491 * because we are unable to write any response due to having already
1492 * sent close_notify.
1494 if (!SSL_CONNECTION_IS_TLS13(s)) {
1495 ssl_release_record(s, rr);
1497 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1500 s->rwstate = SSL_READING;
1501 rbio = SSL_get_rbio(ssl);
1502 BIO_clear_retry_flags(rbio);
1503 BIO_set_retry_read(rbio);
1508 * The peer is continuing to send application data, but we have
1509 * already sent close_notify. If this was expected we should have
1510 * been called via SSL_read() and this would have been handled
1512 * No alert sent because we already sent close_notify
1514 ssl_release_record(s, rr);
1515 SSLfatal(s, SSL_AD_NO_ALERT,
1516 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1522 * For handshake data we have 'fragment' storage, so fill that so that we
1523 * can process the header at a fixed place. This is done after the
1524 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1525 * that we're just going to discard.
1527 if (rr->type == SSL3_RT_HANDSHAKE) {
1528 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1529 unsigned char *dest = s->rlayer.handshake_fragment;
1530 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1532 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1534 n = rr->length; /* available bytes */
1536 /* now move 'n' bytes: */
1537 memcpy(dest + *dest_len, rr->data + rr->off, n);
1541 if (rr->length == 0)
1542 ssl_release_record(s, rr);
1544 if (*dest_len < dest_maxlen)
1545 goto start; /* fragment was too small */
1548 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1549 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1554 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1555 * protocol violation)
1557 if ((s->rlayer.handshake_fragment_len >= 4)
1558 && !ossl_statem_get_in_handshake(s)) {
1559 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1561 /* We found handshake data, so we're going back into init */
1562 ossl_statem_set_in_init(s, 1);
1564 i = s->handshake_func(ssl);
1565 /* SSLfatal() already called if appropriate */
1573 * If we were actually trying to read early data and we found a
1574 * handshake message, then we don't want to continue to try and read
1575 * the application data any more. It won't be "early" now.
1580 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1581 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1584 * In the case where we try to read application data, but we
1585 * trigger an SSL handshake, we return -1 with the retry
1586 * option set. Otherwise renegotiation may cause nasty
1587 * problems in the blocking world
1589 s->rwstate = SSL_READING;
1590 bio = SSL_get_rbio(ssl);
1591 BIO_clear_retry_flags(bio);
1592 BIO_set_retry_read(bio);
1602 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1603 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1604 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1605 * no progress is being made and the peer continually sends unrecognised
1606 * record types, using up resources processing them.
1608 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1610 case SSL3_RT_CHANGE_CIPHER_SPEC:
1612 case SSL3_RT_HANDSHAKE:
1614 * we already handled all of these, with the possible exception of
1615 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1616 * that should not happen when type != rr->type
1618 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1620 case SSL3_RT_APPLICATION_DATA:
1622 * At this point, we were expecting handshake data, but have
1623 * application data. If the library was running inside ssl3_read()
1624 * (i.e. in_read_app_data is set) and it makes sense to read
1625 * application data at this point (session renegotiation not yet
1626 * started), we will indulge it.
1628 if (ossl_statem_app_data_allowed(s)) {
1629 s->s3.in_read_app_data = 2;
1631 } else if (ossl_statem_skip_early_data(s)) {
1633 * This can happen after a client sends a CH followed by early_data,
1634 * but the server responds with a HelloRetryRequest. The server
1635 * reads the next record from the client expecting to find a
1636 * plaintext ClientHello but gets a record which appears to be
1637 * application data. The trial decrypt "works" because null
1638 * decryption was applied. We just skip it and move on to the next
1641 if (!ossl_early_data_count_ok(s, rr->length,
1642 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1643 /* SSLfatal() already called */
1646 ssl_release_record(s, rr);
1649 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1655 void ssl3_record_sequence_update(unsigned char *seq)
1659 for (i = 7; i >= 0; i--) {
1667 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1668 * format and false otherwise.
1670 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1672 if (SSL_CONNECTION_IS_DTLS(rl->s))
1674 return rl->tlsrecs[0].version == SSL2_VERSION;
1677 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1678 static void rlayer_msg_callback_wrapper(int write_p, int version,
1679 int content_type, const void *buf,
1680 size_t len, void *cbarg)
1682 SSL_CONNECTION *s = cbarg;
1683 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1685 if (s->msg_callback != NULL)
1686 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1687 s->msg_callback_arg);
1690 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1691 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1694 SSL_CONNECTION *s = cbarg;
1696 return ssl_security(s, op, bits, nid, other);
1699 static const OSSL_DISPATCH rlayer_dispatch[] = {
1700 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1701 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1702 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1706 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1710 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1711 if (SSL_CONNECTION_IS_DTLS(s))
1712 return &ossl_dtls_record_method;
1714 return &ossl_tls_record_method;
1717 #ifndef OPENSSL_NO_KTLS
1718 /* KTLS does not support renegotiation */
1719 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1720 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1721 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1722 return &ossl_ktls_record_method;
1725 /* Default to the current OSSL_RECORD_METHOD */
1726 return s->rlayer.rrlmethod;
1729 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1731 #ifndef OPENSSL_NO_KTLS
1732 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1734 if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1735 /* KTLS does not support renegotiation so disallow it */
1736 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1739 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rlayer.rrlmethod->set_first_handshake != NULL)
1740 s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 1);
1742 if (s->max_pipelines != 0 && s->rlayer.rrlmethod->set_max_pipelines != NULL)
1743 s->rlayer.rrlmethod->set_max_pipelines(s->rlayer.rrl, s->max_pipelines);
1748 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1749 int direction, int level,
1750 unsigned char *key, size_t keylen,
1751 unsigned char *iv, size_t ivlen,
1752 unsigned char *mackey, size_t mackeylen,
1753 const EVP_CIPHER *ciph, size_t taglen,
1754 int mactype, const EVP_MD *md,
1755 const SSL_COMP *comp)
1757 OSSL_PARAM options[5], *opts = options;
1758 OSSL_PARAM settings[6], *set = settings;
1759 const OSSL_RECORD_METHOD *origmeth = s->rlayer.rrlmethod;
1760 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1761 const OSSL_RECORD_METHOD *meth;
1762 int use_etm, stream_mac = 0, tlstree = 0;
1763 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1764 int use_early_data = 0;
1765 uint32_t max_early_data;
1767 meth = ssl_select_next_record_layer(s, level);
1769 if (s->rlayer.rrlmethod != NULL && !s->rlayer.rrlmethod->free(s->rlayer.rrl)) {
1770 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1775 s->rlayer.rrlmethod = meth;
1777 if (!ossl_assert(s->rlayer.rrlmethod != NULL)) {
1778 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1782 /* Parameters that *may* be supported by a record layer if passed */
1783 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1785 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1787 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1788 &s->rlayer.default_read_buf_len);
1789 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1790 &s->rlayer.read_ahead);
1791 *opts = OSSL_PARAM_construct_end();
1793 /* Parameters that *must* be supported by a record layer if passed */
1794 if (direction == OSSL_RECORD_DIRECTION_READ) {
1795 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1796 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1799 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1802 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1803 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1806 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1811 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1815 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1819 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1822 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1823 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1825 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1826 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1830 * The record layer must check the amount of early data sent or received
1831 * using the early keys. A server also needs to worry about rejected early
1832 * data that might arrive when the handshake keys are in force.
1834 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1835 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1836 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1837 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1838 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1839 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1841 if (use_early_data) {
1842 max_early_data = ossl_get_max_early_data(s);
1844 if (max_early_data != 0)
1845 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1849 *set = OSSL_PARAM_construct_end();
1853 BIO *prev = s->rlayer.rrlnext;
1854 unsigned int epoch = 0;;
1856 if (SSL_CONNECTION_IS_DTLS(s)
1857 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1858 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1860 if (SSL_CONNECTION_IS_DTLS(s))
1861 s->rlayer.rrlnext = BIO_new(BIO_s_dgram_mem());
1863 s->rlayer.rrlnext = BIO_new(BIO_s_mem());
1865 if (s->rlayer.rrlnext == NULL) {
1867 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1871 rlret = s->rlayer.rrlmethod->new_record_layer(sctx->libctx,
1874 direction, level, epoch,
1875 key, keylen, iv, ivlen,
1876 mackey, mackeylen, ciph,
1877 taglen, mactype, md, comp,
1879 s->rlayer.rrlnext, NULL,
1880 NULL, settings, options,
1885 case OSSL_RECORD_RETURN_FATAL:
1886 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1889 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1890 if (s->rlayer.rrlmethod != origmeth && origmeth != NULL) {
1892 * We tried a new record layer method, but it didn't work out,
1893 * so we fallback to the original method and try again
1895 s->rlayer.rrlmethod = origmeth;
1898 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1901 case OSSL_RECORD_RETURN_SUCCESS:
1905 /* Should not happen */
1906 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1912 return ssl_post_record_layer_select(s);