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)
33 RECORD_LAYER_set_first_record(&s->rlayer);
34 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
37 void RECORD_LAYER_clear(RECORD_LAYER *rl)
39 rl->rstate = SSL_ST_READ_HEADER;
42 * Do I need to clear read_ahead? As far as I can tell read_ahead did not
43 * previously get reset by SSL_clear...so I'll keep it that way..but is
48 rl->packet_length = 0;
50 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
51 rl->handshake_fragment_len = 0;
57 SSL3_BUFFER_clear(&rl->rbuf);
58 ssl3_release_write_buffer(rl->s);
60 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
62 RECORD_LAYER_reset_read_sequence(rl);
63 RECORD_LAYER_reset_write_sequence(rl);
66 DTLS_RECORD_LAYER_clear(rl);
69 void RECORD_LAYER_release(RECORD_LAYER *rl)
71 if (SSL3_BUFFER_is_initialised(&rl->rbuf))
72 ssl3_release_read_buffer(rl->s);
73 if (rl->numwpipes > 0)
74 ssl3_release_write_buffer(rl->s);
75 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
78 /* Checks if we have unprocessed read ahead data pending */
79 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
81 return rl->s->rrlmethod->unprocessed_read_pending(rl->s->rrl);
84 /* Checks if we have decrypted unread record data pending */
85 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
87 return (rl->curr_rec < rl->num_recs)
88 || rl->s->rrlmethod->processed_read_pending(rl->s->rrl);
91 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
93 return (rl->numwpipes > 0)
94 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
97 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
99 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
102 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
104 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
107 size_t ssl3_pending(const SSL *s)
110 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
115 if (sc->rlayer.rstate == SSL_ST_READ_BODY)
118 if (SSL_CONNECTION_IS_DTLS(sc)) {
122 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
123 while ((item = pqueue_next(&iter)) != NULL) {
125 num += rdata->length;
129 for (i = 0; i < sc->rlayer.num_recs; i++) {
130 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
132 num += sc->rlayer.tlsrecs[i].length;
138 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
140 ctx->default_read_buf_len = len;
143 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
145 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
149 SSL3_BUFFER_set_default_len(sc->rrlmethod->get0_rbuf(sc->rrl), len);
152 const char *SSL_rstate_string_long(const SSL *s)
154 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
159 switch (sc->rlayer.rstate) {
160 case SSL_ST_READ_HEADER:
161 return "read header";
162 case SSL_ST_READ_BODY:
164 case SSL_ST_READ_DONE:
171 const char *SSL_rstate_string(const SSL *s)
173 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
178 switch (sc->rlayer.rstate) {
179 case SSL_ST_READ_HEADER:
181 case SSL_ST_READ_BODY:
183 case SSL_ST_READ_DONE:
192 * Call this to write data in records of type 'type' It will return <= 0 if
193 * not all data has been sent or non-blocking IO.
195 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
198 const unsigned char *buf = buf_;
200 size_t n, max_send_fragment, split_send_fragment, maxpipes;
201 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
207 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
212 wb = &s->rlayer.wbuf[0];
213 s->rwstate = SSL_NOTHING;
214 tot = s->rlayer.wnum;
216 * ensure that if we end up with a smaller value of data to write out
217 * than the original len from a write which didn't complete for
218 * non-blocking I/O and also somehow ended up avoiding the check for
219 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
220 * possible to end up with (len-tot) as a large number that will then
221 * promptly send beyond the end of the users buffer ... so we trap and
222 * report the error in a way the user will notice
224 if ((len < s->rlayer.wnum)
225 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
226 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
230 if (s->early_data_state == SSL_EARLY_DATA_WRITING
231 && !ossl_early_data_count_ok(s, len, 0, 1)) {
232 /* SSLfatal() already called */
239 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
240 * into init unless we have writes pending - in which case we should finish
243 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
244 || s->ext.extra_tickets_expected > 0))
245 ossl_statem_set_in_init(s, 1);
248 * When writing early data on the server side we could be "in_init" in
249 * between receiving the EoED and the CF - but we don't want to handle those
252 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
253 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
254 i = s->handshake_func(ssl);
255 /* SSLfatal() already called */
264 * first check if there is a SSL3_BUFFER still being written out. This
265 * will happen with non blocking IO
268 /* SSLfatal() already called if appropriate */
269 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
272 /* XXX should we ssl3_release_write_buffer if i<0? */
273 s->rlayer.wnum = tot;
276 tot += tmpwrit; /* this might be last fragment */
278 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
280 * Depending on platform multi-block can deliver several *times*
281 * better performance. Downside is that it has to allocate
282 * jumbo buffer to accommodate up to 8 records, but the
283 * compromise is considered worthy.
285 if (type == SSL3_RT_APPLICATION_DATA
286 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
287 && s->compress == NULL
288 && s->msg_callback == NULL
290 && SSL_USE_EXPLICIT_IV(s)
291 && !BIO_get_ktls_send(s->wbio)
292 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
293 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
294 unsigned char aad[13];
295 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
299 /* minimize address aliasing conflicts */
300 if ((max_send_fragment & 0xfff) == 0)
301 max_send_fragment -= 512;
303 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
304 ssl3_release_write_buffer(s);
306 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
307 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
308 (int)max_send_fragment, NULL);
310 if (len >= 8 * max_send_fragment)
315 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
316 /* SSLfatal() already called */
319 } else if (tot == len) { /* done? */
320 /* free jumbo buffer */
321 ssl3_release_write_buffer(s);
328 if (n < 4 * max_send_fragment) {
329 /* free jumbo buffer */
330 ssl3_release_write_buffer(s);
334 if (s->s3.alert_dispatch) {
335 i = ssl->method->ssl_dispatch_alert(ssl);
337 /* SSLfatal() already called if appropriate */
338 s->rlayer.wnum = tot;
343 if (n >= 8 * max_send_fragment)
344 nw = max_send_fragment * (mb_param.interleave = 8);
346 nw = max_send_fragment * (mb_param.interleave = 4);
348 memcpy(aad, s->rlayer.write_sequence, 8);
350 aad[9] = (unsigned char)(s->version >> 8);
351 aad[10] = (unsigned char)(s->version);
358 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
359 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
360 sizeof(mb_param), &mb_param);
361 packlen = (size_t)packleni;
362 if (packleni <= 0 || packlen > wb->len) { /* never happens */
363 /* free jumbo buffer */
364 ssl3_release_write_buffer(s);
368 mb_param.out = wb->buf;
369 mb_param.inp = &buf[tot];
372 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
373 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
374 sizeof(mb_param), &mb_param) <= 0)
377 s->rlayer.write_sequence[7] += mb_param.interleave;
378 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
380 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
386 s->rlayer.wpend_tot = nw;
387 s->rlayer.wpend_buf = &buf[tot];
388 s->rlayer.wpend_type = type;
389 s->rlayer.wpend_ret = nw;
391 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
393 /* SSLfatal() already called if appropriate */
394 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
395 /* free jumbo buffer */
396 ssl3_release_write_buffer(s);
398 s->rlayer.wnum = tot;
402 /* free jumbo buffer */
403 ssl3_release_write_buffer(s);
404 *written = tot + tmpwrit;
411 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
412 if (tot == len) { /* done? */
413 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
414 ssl3_release_write_buffer(s);
422 max_send_fragment = ssl_get_max_send_fragment(s);
423 split_send_fragment = ssl_get_split_send_fragment(s);
425 * If max_pipelines is 0 then this means "undefined" and we default to
426 * 1 pipeline. Similarly if the cipher does not support pipelined
427 * processing then we also only use 1 pipeline, or if we're not using
430 maxpipes = s->max_pipelines;
431 if (maxpipes > SSL_MAX_PIPELINES) {
433 * We should have prevented this when we set max_pipelines so we
436 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
440 || s->enc_write_ctx == NULL
441 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
442 & EVP_CIPH_FLAG_PIPELINE) == 0
443 || !SSL_USE_EXPLICIT_IV(s))
445 if (max_send_fragment == 0
446 || split_send_fragment == 0
447 || split_send_fragment > max_send_fragment) {
449 * We should have prevented this when we set/get the split and max send
450 * fragments so we shouldn't get here
452 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
457 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
463 numpipes = ((n - 1) / split_send_fragment) + 1;
464 if (numpipes > maxpipes)
467 if (n / numpipes >= max_send_fragment) {
469 * We have enough data to completely fill all available
472 for (j = 0; j < numpipes; j++) {
473 pipelens[j] = max_send_fragment;
476 /* We can partially fill all available pipelines */
477 tmppipelen = n / numpipes;
478 remain = n % numpipes;
479 for (j = 0; j < numpipes; j++) {
480 pipelens[j] = tmppipelen;
486 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
489 /* SSLfatal() already called if appropriate */
490 /* XXX should we ssl3_release_write_buffer if i<0? */
491 s->rlayer.wnum = tot;
496 (type == SSL3_RT_APPLICATION_DATA &&
497 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
499 * next chunk of data should get another prepended empty fragment
500 * in ciphersuites with known-IV weakness:
502 s->s3.empty_fragment_done = 0;
505 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
506 && !SSL_CONNECTION_IS_DTLS(s))
507 ssl3_release_write_buffer(s);
509 *written = tot + tmpwrit;
518 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
519 size_t *pipelens, size_t numpipes,
520 int create_empty_fragment, size_t *written)
522 WPACKET pkt[SSL_MAX_PIPELINES];
523 SSL3_RECORD wr[SSL_MAX_PIPELINES];
526 unsigned char *recordstart;
527 int i, mac_size, clear = 0;
528 size_t prefix_len = 0;
533 size_t totlen = 0, len, wpinited = 0;
536 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
538 for (j = 0; j < numpipes; j++)
539 totlen += pipelens[j];
541 * first check if there is a SSL3_BUFFER still being written out. This
542 * will happen with non blocking IO
544 if (RECORD_LAYER_write_pending(&s->rlayer)) {
545 /* Calls SSLfatal() as required */
546 return ssl3_write_pending(s, type, buf, totlen, written);
549 /* If we have an alert to send, lets send it */
550 if (s->s3.alert_dispatch) {
551 i = ssl->method->ssl_dispatch_alert(ssl);
553 /* SSLfatal() already called if appropriate */
556 /* if it went, fall through and send more stuff */
559 if (s->rlayer.numwpipes < numpipes) {
560 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
561 /* SSLfatal() already called */
566 if (totlen == 0 && !create_empty_fragment)
572 || (s->enc_write_ctx == NULL)
573 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
574 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
577 mac_size = EVP_MD_CTX_get_size(s->write_hash);
579 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
585 * 'create_empty_fragment' is true only when this function calls itself
587 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
589 * countermeasure against known-IV weakness in CBC ciphersuites (see
590 * http://www.openssl.org/~bodo/tls-cbc.txt)
593 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
595 * recursive function call with 'create_empty_fragment' set; this
596 * prepares and buffers the data for an empty fragment (these
597 * 'prefix_len' bytes are sent out later together with the actual
600 size_t tmppipelen = 0;
603 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
605 /* SSLfatal() already called if appropriate */
610 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
611 /* insufficient space */
612 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
617 s->s3.empty_fragment_done = 1;
620 using_ktls = BIO_get_ktls_send(s->wbio);
623 * ktls doesn't modify the buffer, but to avoid a warning we need to
624 * discard the const qualifier.
625 * This doesn't leak memory because the buffers have been released when
628 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
629 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
630 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
631 goto wpacket_init_complete;
634 if (create_empty_fragment) {
635 wb = &s->rlayer.wbuf[0];
636 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
638 * extra fragment would be couple of cipher blocks, which would be
639 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
640 * payload, then we can just pretend we simply have two headers.
642 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
643 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
645 SSL3_BUFFER_set_offset(wb, align);
646 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
647 SSL3_BUFFER_get_len(wb), 0)
648 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
649 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
653 } else if (prefix_len) {
654 wb = &s->rlayer.wbuf[0];
655 if (!WPACKET_init_static_len(&pkt[0],
656 SSL3_BUFFER_get_buf(wb),
657 SSL3_BUFFER_get_len(wb), 0)
658 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
659 + prefix_len, NULL)) {
660 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
665 for (j = 0; j < numpipes; j++) {
668 wb = &s->rlayer.wbuf[j];
669 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
670 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
671 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
673 SSL3_BUFFER_set_offset(wb, align);
674 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
675 SSL3_BUFFER_get_len(wb), 0)
676 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
677 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
684 /* Explicit IV length, block ciphers appropriate version flag */
685 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
686 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
687 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
688 if (mode == EVP_CIPH_CBC_MODE) {
689 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
691 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
696 } else if (mode == EVP_CIPH_GCM_MODE) {
697 /* Need explicit part of IV for GCM mode */
698 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
699 } else if (mode == EVP_CIPH_CCM_MODE) {
700 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
704 wpacket_init_complete:
707 /* Clear our SSL3_RECORD structures */
708 memset(wr, 0, sizeof(wr));
709 for (j = 0; j < numpipes; j++) {
710 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
712 unsigned char *compressdata = NULL;
714 unsigned int rectype;
720 * In TLSv1.3, once encrypting, we always use application data for the
723 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
724 && s->enc_write_ctx != NULL
725 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
726 || type != SSL3_RT_ALERT))
727 rectype = SSL3_RT_APPLICATION_DATA;
730 SSL3_RECORD_set_type(thiswr, rectype);
733 * Some servers hang if initial client hello is larger than 256 bytes
734 * and record version number > TLS 1.0
736 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
738 && TLS1_get_version(ssl) > TLS1_VERSION
739 && s->hello_retry_request == SSL_HRR_NONE)
740 version = TLS1_VERSION;
741 SSL3_RECORD_set_rec_version(thiswr, version);
743 maxcomplen = pipelens[j];
744 if (s->compress != NULL)
745 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
748 * When using offload kernel will write the header.
749 * Otherwise write the header now
752 && (!WPACKET_put_bytes_u8(thispkt, rectype)
753 || !WPACKET_put_bytes_u16(thispkt, version)
754 || !WPACKET_start_sub_packet_u16(thispkt)
756 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
758 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
760 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
764 /* lets setup the record stuff. */
765 SSL3_RECORD_set_data(thiswr, compressdata);
766 SSL3_RECORD_set_length(thiswr, pipelens[j]);
767 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
768 totlen += pipelens[j];
771 * we now 'read' from thiswr->input, thiswr->length bytes into
775 /* first we compress */
776 if (s->compress != NULL) {
777 if (!ssl3_do_compress(s, thiswr)
778 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
779 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
784 SSL3_RECORD_reset_data(&wr[j]);
786 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
787 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
790 SSL3_RECORD_reset_input(&wr[j]);
794 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
796 && s->enc_write_ctx != NULL
797 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
798 || type != SSL3_RT_ALERT)) {
799 size_t rlen, max_send_fragment;
801 if (!WPACKET_put_bytes_u8(thispkt, type)) {
802 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
805 SSL3_RECORD_add_length(thiswr, 1);
807 /* Add TLS1.3 padding */
808 max_send_fragment = ssl_get_max_send_fragment(s);
809 rlen = SSL3_RECORD_get_length(thiswr);
810 if (rlen < max_send_fragment) {
812 size_t max_padding = max_send_fragment - rlen;
813 if (s->record_padding_cb != NULL) {
814 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
815 } else if (s->block_padding > 0) {
816 size_t mask = s->block_padding - 1;
819 /* optimize for power of 2 */
820 if ((s->block_padding & mask) == 0)
821 remainder = rlen & mask;
823 remainder = rlen % s->block_padding;
824 /* don't want to add a block of padding if we don't have to */
828 padding = s->block_padding - remainder;
831 /* do not allow the record to exceed max plaintext length */
832 if (padding > max_padding)
833 padding = max_padding;
834 if (!WPACKET_memset(thispkt, 0, padding)) {
835 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
836 ERR_R_INTERNAL_ERROR);
839 SSL3_RECORD_add_length(thiswr, padding);
845 * we should still have the output to thiswr->data and the input from
846 * wr->input. Length should be thiswr->length. thiswr->data still points
850 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
853 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
854 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
855 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
861 * Reserve some bytes for any growth that may occur during encryption.
862 * This will be at most one cipher block or the tag length if using
863 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
866 if (!WPACKET_reserve_bytes(thispkt,
867 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
870 * We also need next the amount of bytes written to this
873 || !WPACKET_get_length(thispkt, &len)) {
874 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
878 /* Get a pointer to the start of this record excluding header */
879 recordstart = WPACKET_get_curr(thispkt) - len;
880 SSL3_RECORD_set_data(thiswr, recordstart);
881 SSL3_RECORD_reset_input(thiswr);
882 SSL3_RECORD_set_length(thiswr, len);
886 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
888 * We haven't actually negotiated the version yet, but we're trying to
889 * send early data - so we need to use the tls13enc function.
891 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
892 if (!ossl_statem_in_error(s)) {
893 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
899 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
901 if (!ossl_statem_in_error(s)) {
902 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
909 for (j = 0; j < numpipes; j++) {
918 /* Allocate bytes for the encryption overhead */
919 if (!WPACKET_get_length(thispkt, &origlen)
920 /* Encryption should never shrink the data! */
921 || origlen > thiswr->length
922 || (thiswr->length > origlen
923 && !WPACKET_allocate_bytes(thispkt,
924 thiswr->length - origlen,
926 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
929 if (SSL_WRITE_ETM(s) && mac_size != 0) {
932 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
933 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
934 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
937 SSL3_RECORD_add_length(thiswr, mac_size);
940 if (!WPACKET_get_length(thispkt, &len)
941 || !WPACKET_close(thispkt)) {
942 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
946 if (s->msg_callback) {
947 recordstart = WPACKET_get_curr(thispkt) - len
948 - SSL3_RT_HEADER_LENGTH;
949 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
950 SSL3_RT_HEADER_LENGTH, ssl,
951 s->msg_callback_arg);
953 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
954 unsigned char ctype = type;
956 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
957 &ctype, 1, ssl, s->msg_callback_arg);
961 if (!WPACKET_finish(thispkt)) {
962 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
966 /* header is added by the kernel when using offload */
967 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
969 if (create_empty_fragment) {
971 * we are in a recursive call; just return the length, don't write
975 /* We should never be pipelining an empty fragment!! */
976 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
979 *written = SSL3_RECORD_get_length(thiswr);
985 * we should now have thiswr->data pointing to the encrypted data, which
986 * is thiswr->length long
988 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
991 /* now let's set up wb */
992 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
993 prefix_len + SSL3_RECORD_get_length(thiswr));
997 * memorize arguments so that ssl3_write_pending can detect bad write
1000 s->rlayer.wpend_tot = totlen;
1001 s->rlayer.wpend_buf = buf;
1002 s->rlayer.wpend_type = type;
1003 s->rlayer.wpend_ret = totlen;
1005 /* we now just need to write the buffer */
1006 return ssl3_write_pending(s, type, buf, totlen, written);
1008 for (j = 0; j < wpinited; j++)
1009 WPACKET_cleanup(&pkt[j]);
1013 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1015 * Return values are as per SSL_write()
1017 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1018 size_t len, size_t *written)
1021 SSL3_BUFFER *wb = s->rlayer.wbuf;
1025 if ((s->rlayer.wpend_tot > len)
1026 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1027 && (s->rlayer.wpend_buf != buf))
1028 || (s->rlayer.wpend_type != type)) {
1029 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1034 /* Loop until we find a buffer we haven't written out yet */
1035 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1036 && currbuf < s->rlayer.numwpipes - 1) {
1041 if (s->wbio != NULL) {
1042 s->rwstate = SSL_WRITING;
1045 * To prevent coalescing of control and data messages,
1046 * such as in buffer_write, we flush the BIO
1048 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1049 i = BIO_flush(s->wbio);
1052 BIO_set_ktls_ctrl_msg(s->wbio, type);
1054 i = BIO_write(s->wbio, (char *)
1055 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1056 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1057 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1061 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1066 * When an empty fragment is sent on a connection using KTLS,
1067 * it is sent as a write of zero bytes. If this zero byte
1068 * write succeeds, i will be 0 rather than a non-zero value.
1069 * Treat i == 0 as success rather than an error for zero byte
1070 * writes to permit this case.
1072 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1073 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1074 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1075 if (currbuf + 1 < s->rlayer.numwpipes)
1077 s->rwstate = SSL_NOTHING;
1078 *written = s->rlayer.wpend_ret;
1080 } else if (i <= 0) {
1081 if (SSL_CONNECTION_IS_DTLS(s)) {
1083 * For DTLS, just drop it. That's kind of the whole point in
1084 * using a datagram service
1086 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1090 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1091 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1095 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1098 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1100 if (ret == OSSL_RECORD_RETURN_RETRY) {
1101 s->rwstate = SSL_READING;
1104 s->rwstate = SSL_NOTHING;
1105 if (ret == OSSL_RECORD_RETURN_EOF) {
1106 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1107 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1108 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1111 ERR_set_debug(file, line, 0);
1112 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1113 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1115 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1117 ERR_set_debug(file, line, 0);
1118 ossl_statem_fatal(s, s->rrlmethod->get_alert_code(s->rrl),
1119 SSL_R_RECORD_LAYER_FAILURE, NULL);
1122 * The record layer distinguishes the cases of EOF, non-fatal
1123 * err and retry. Upper layers do not.
1124 * If we got a retry or success then *ret is already correct,
1125 * otherwise we need to convert the return value.
1128 * TODO(RECLAYER): What does a non fatal err that isn't a retry even
1131 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1133 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1140 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
1142 if (rr->rechandle != NULL) {
1143 /* The record layer allocated the buffers for this record */
1144 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1146 /* We allocated the buffers for this record (only happens with DTLS) */
1147 OPENSSL_free(rr->data);
1149 s->rlayer.curr_rec++;
1153 * Return up to 'len' payload bytes received in 'type' records.
1154 * 'type' is one of the following:
1156 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1157 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1158 * - 0 (during a shutdown, no data has to be returned)
1160 * If we don't have stored data to work from, read a SSL/TLS record first
1161 * (possibly multiple records if we still don't have anything to return).
1163 * This function must handle any surprises the peer may have for us, such as
1164 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1165 * messages are treated as if they were handshake messages *if* the |recvd_type|
1166 * argument is non NULL.
1167 * Also if record payloads contain fragments too small to process, we store
1168 * them until there is enough for the respective protocol (the record protocol
1169 * may use arbitrary fragmentation and even interleaving):
1170 * Change cipher spec protocol
1171 * just 1 byte needed, no need for keeping anything stored
1173 * 2 bytes needed (AlertLevel, AlertDescription)
1174 * Handshake protocol
1175 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1176 * to detect unexpected Client Hello and Hello Request messages
1177 * here, anything else is handled by higher layers
1178 * Application data protocol
1179 * none of our business
1181 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1182 size_t len, int peek, size_t *readbytes)
1185 size_t n, curr_rec, totalbytes;
1187 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1189 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1191 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1194 && (type != SSL3_RT_APPLICATION_DATA)
1195 && (type != SSL3_RT_HANDSHAKE))
1196 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1197 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1201 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1202 /* (partially) satisfy request from storage */
1204 unsigned char *src = s->rlayer.handshake_fragment;
1205 unsigned char *dst = buf;
1210 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1213 s->rlayer.handshake_fragment_len--;
1216 /* move any remaining fragment bytes: */
1217 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1218 s->rlayer.handshake_fragment[k] = *src++;
1220 if (recvd_type != NULL)
1221 *recvd_type = SSL3_RT_HANDSHAKE;
1228 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1231 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1232 /* type == SSL3_RT_APPLICATION_DATA */
1233 i = s->handshake_func(ssl);
1234 /* SSLfatal() already called */
1241 s->rwstate = SSL_NOTHING;
1244 * For each record 'i' up to |num_recs]
1245 * rr[i].type - is the type of record
1246 * rr[i].data, - data
1247 * rr[i].off, - offset into 'data' for next read
1248 * rr[i].length, - number of bytes.
1250 /* get new records if necessary */
1251 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1252 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1254 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1256 ret = HANDLE_RLAYER_RETURN(s,
1257 s->rrlmethod->read_record(s->rrl, &rr->rechandle,
1258 &rr->version, &rr->type,
1259 &rr->data, &rr->length,
1262 /* SSLfatal() already called if appropriate */
1266 s->rlayer.num_recs++;
1267 } while (s->rrlmethod->processed_read_pending(s->rrl)
1268 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1270 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1272 if (s->rlayer.handshake_fragment_len > 0
1273 && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1274 && SSL_CONNECTION_IS_TLS13(s)) {
1275 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1276 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1281 * Reset the count of consecutive warning alerts if we've got a non-empty
1282 * record that isn't an alert.
1284 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1285 s->rlayer.alert_count = 0;
1287 /* we now have a packet which can be read and processed */
1289 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1290 * reset by ssl3_get_finished */
1291 && (rr->type != SSL3_RT_HANDSHAKE)) {
1292 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1293 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1298 * If the other end has shut down, throw anything we read away (even in
1301 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1302 s->rlayer.curr_rec++;
1303 s->rwstate = SSL_NOTHING;
1307 if (type == rr->type
1308 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1309 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1312 * SSL3_RT_APPLICATION_DATA or
1313 * SSL3_RT_HANDSHAKE or
1314 * SSL3_RT_CHANGE_CIPHER_SPEC
1317 * make sure that we are not getting application data when we are
1318 * doing a handshake for the first time
1320 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1321 && s->enc_read_ctx == NULL) {
1322 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1326 if (type == SSL3_RT_HANDSHAKE
1327 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1328 && s->rlayer.handshake_fragment_len > 0) {
1329 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1333 if (recvd_type != NULL)
1334 *recvd_type = rr->type;
1338 * Skip a zero length record. This ensures multiple calls to
1339 * SSL_read() with a zero length buffer will eventually cause
1340 * SSL_pending() to report data as being available.
1342 if (rr->length == 0)
1343 ssl_release_record(s, rr);
1349 curr_rec = s->rlayer.curr_rec;
1351 if (len - totalbytes > rr->length)
1354 n = len - totalbytes;
1356 memcpy(buf, &(rr->data[rr->off]), n);
1359 /* Mark any zero length record as consumed CVE-2016-6305 */
1360 if (rr->length == 0)
1361 ssl_release_record(s, rr);
1363 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1364 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1367 if (rr->length == 0) {
1368 /* TODO(RECLAYER): What to do with this? Is it needed? */
1370 s->rlayer.rstate = SSL_ST_READ_HEADER;
1372 ssl_release_record(s, rr);
1376 || (peek && n == rr->length)) {
1381 } while (type == SSL3_RT_APPLICATION_DATA
1382 && curr_rec < s->rlayer.num_recs
1383 && totalbytes < len);
1384 if (totalbytes == 0) {
1385 /* We must have read empty records. Get more data */
1388 /* TODO(RECLAYER): FIX ME */
1390 if (!peek && curr_rec == s->rlayer.num_recs
1391 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1392 && SSL3_BUFFER_get_left(rbuf) == 0)
1393 ssl3_release_read_buffer(s);
1395 *readbytes = totalbytes;
1400 * If we get here, then type != rr->type; if we have a handshake message,
1401 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1402 * were actually expecting a CCS).
1406 * Lets just double check that we've not got an SSLv2 record
1408 if (rr->version == SSL2_VERSION) {
1410 * Should never happen. ssl3_get_record() should only give us an SSLv2
1411 * record back if this is the first packet and we are looking for an
1412 * initial ClientHello. Therefore |type| should always be equal to
1413 * |rr->type|. If not then something has gone horribly wrong
1415 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1419 if (ssl->method->version == TLS_ANY_VERSION
1420 && (s->server || rr->type != SSL3_RT_ALERT)) {
1422 * If we've got this far and still haven't decided on what version
1423 * we're using then this must be a client side alert we're dealing
1424 * with. We shouldn't be receiving anything other than a ClientHello
1425 * if we are a server.
1427 s->version = rr->version;
1428 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1433 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1434 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1437 if (rr->type == SSL3_RT_ALERT) {
1438 unsigned int alert_level, alert_descr;
1439 unsigned char *alert_bytes = rr->data
1443 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1444 || !PACKET_get_1(&alert, &alert_level)
1445 || !PACKET_get_1(&alert, &alert_descr)
1446 || PACKET_remaining(&alert) != 0) {
1447 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1451 if (s->msg_callback)
1452 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1453 s->msg_callback_arg);
1455 if (s->info_callback != NULL)
1456 cb = s->info_callback;
1457 else if (ssl->ctx->info_callback != NULL)
1458 cb = ssl->ctx->info_callback;
1461 j = (alert_level << 8) | alert_descr;
1462 cb(ssl, SSL_CB_READ_ALERT, j);
1465 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1466 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1467 s->s3.warn_alert = alert_descr;
1468 ssl_release_record(s, rr);
1470 s->rlayer.alert_count++;
1471 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1472 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1473 SSL_R_TOO_MANY_WARN_ALERTS);
1479 * Apart from close_notify the only other warning alert in TLSv1.3
1480 * is user_cancelled - which we just ignore.
1482 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1484 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1485 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1486 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1488 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1489 s->rwstate = SSL_NOTHING;
1490 s->s3.fatal_alert = alert_descr;
1491 SSLfatal_data(s, SSL_AD_NO_ALERT,
1492 SSL_AD_REASON_OFFSET + alert_descr,
1493 "SSL alert number %d", alert_descr);
1494 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1495 ssl_release_record(s, rr);
1496 SSL_CTX_remove_session(s->session_ctx, s->session);
1498 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1500 * This is a warning but we receive it if we requested
1501 * renegotiation and the peer denied it. Terminate with a fatal
1502 * alert because if application tried to renegotiate it
1503 * presumably had a good reason and expects it to succeed. In
1504 * future we might have a renegotiation where we don't care if
1505 * the peer refused it where we carry on.
1507 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1509 } else if (alert_level == SSL3_AL_WARNING) {
1510 /* We ignore any other warning alert in TLSv1.2 and below */
1514 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1518 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1519 if (rr->type == SSL3_RT_HANDSHAKE) {
1523 * We ignore any handshake messages sent to us unless they are
1524 * TLSv1.3 in which case we want to process them. For all other
1525 * handshake messages we can't do anything reasonable with them
1526 * because we are unable to write any response due to having already
1527 * sent close_notify.
1529 if (!SSL_CONNECTION_IS_TLS13(s)) {
1530 ssl_release_record(s, rr);
1532 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1535 s->rwstate = SSL_READING;
1536 rbio = SSL_get_rbio(ssl);
1537 BIO_clear_retry_flags(rbio);
1538 BIO_set_retry_read(rbio);
1543 * The peer is continuing to send application data, but we have
1544 * already sent close_notify. If this was expected we should have
1545 * been called via SSL_read() and this would have been handled
1547 * No alert sent because we already sent close_notify
1549 ssl_release_record(s, rr);
1550 SSLfatal(s, SSL_AD_NO_ALERT,
1551 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1557 * For handshake data we have 'fragment' storage, so fill that so that we
1558 * can process the header at a fixed place. This is done after the
1559 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1560 * that we're just going to discard.
1562 if (rr->type == SSL3_RT_HANDSHAKE) {
1563 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1564 unsigned char *dest = s->rlayer.handshake_fragment;
1565 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1567 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1569 n = rr->length; /* available bytes */
1571 /* now move 'n' bytes: */
1572 memcpy(dest + *dest_len, rr->data + rr->off, n);
1576 if (rr->length == 0)
1577 ssl_release_record(s, rr);
1579 if (*dest_len < dest_maxlen)
1580 goto start; /* fragment was too small */
1583 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1584 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1589 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1590 * protocol violation)
1592 if ((s->rlayer.handshake_fragment_len >= 4)
1593 && !ossl_statem_get_in_handshake(s)) {
1594 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1596 /* We found handshake data, so we're going back into init */
1597 ossl_statem_set_in_init(s, 1);
1599 i = s->handshake_func(ssl);
1600 /* SSLfatal() already called if appropriate */
1608 * If we were actually trying to read early data and we found a
1609 * handshake message, then we don't want to continue to try and read
1610 * the application data any more. It won't be "early" now.
1615 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1616 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1619 * In the case where we try to read application data, but we
1620 * trigger an SSL handshake, we return -1 with the retry
1621 * option set. Otherwise renegotiation may cause nasty
1622 * problems in the blocking world
1624 s->rwstate = SSL_READING;
1625 bio = SSL_get_rbio(ssl);
1626 BIO_clear_retry_flags(bio);
1627 BIO_set_retry_read(bio);
1637 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1638 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1639 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1640 * no progress is being made and the peer continually sends unrecognised
1641 * record types, using up resources processing them.
1643 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1645 case SSL3_RT_CHANGE_CIPHER_SPEC:
1647 case SSL3_RT_HANDSHAKE:
1649 * we already handled all of these, with the possible exception of
1650 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1651 * that should not happen when type != rr->type
1653 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1655 case SSL3_RT_APPLICATION_DATA:
1657 * At this point, we were expecting handshake data, but have
1658 * application data. If the library was running inside ssl3_read()
1659 * (i.e. in_read_app_data is set) and it makes sense to read
1660 * application data at this point (session renegotiation not yet
1661 * started), we will indulge it.
1663 if (ossl_statem_app_data_allowed(s)) {
1664 s->s3.in_read_app_data = 2;
1666 } else if (ossl_statem_skip_early_data(s)) {
1668 * This can happen after a client sends a CH followed by early_data,
1669 * but the server responds with a HelloRetryRequest. The server
1670 * reads the next record from the client expecting to find a
1671 * plaintext ClientHello but gets a record which appears to be
1672 * application data. The trial decrypt "works" because null
1673 * decryption was applied. We just skip it and move on to the next
1676 if (!ossl_early_data_count_ok(s, rr->length,
1677 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1678 /* SSLfatal() already called */
1681 ssl_release_record(s, rr);
1684 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1690 void ssl3_record_sequence_update(unsigned char *seq)
1694 for (i = 7; i >= 0; i--) {
1702 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1703 * format and false otherwise.
1705 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1707 if (SSL_CONNECTION_IS_DTLS(rl->s))
1709 return rl->tlsrecs[0].version == SSL2_VERSION;
1713 * Returns the length in bytes of the current rrec
1715 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1717 return SSL3_RECORD_get_length(&rl->rrec[0]);
1720 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1721 static void rlayer_msg_callback_wrapper(int write_p, int version,
1722 int content_type, const void *buf,
1723 size_t len, void *cbarg)
1725 SSL_CONNECTION *s = cbarg;
1726 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1728 if (s->msg_callback != NULL)
1729 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1730 s->msg_callback_arg);
1733 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1734 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1737 SSL_CONNECTION *s = cbarg;
1739 return ssl_security(s, op, bits, nid, other);
1742 static const OSSL_DISPATCH rlayer_dispatch[] = {
1743 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1744 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1745 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1749 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1753 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1754 if (SSL_CONNECTION_IS_DTLS(s))
1755 return &ossl_dtls_record_method;
1757 return &ossl_tls_record_method;
1760 #ifndef OPENSSL_NO_KTLS
1761 /* KTLS does not support renegotiation */
1762 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1763 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1764 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1765 return &ossl_ktls_record_method;
1768 /* Default to the current OSSL_RECORD_METHOD */
1769 return s->rrlmethod;
1772 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1774 #ifndef OPENSSL_NO_KTLS
1775 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1777 if (s->rrlmethod == &ossl_ktls_record_method) {
1778 /* KTLS does not support renegotiation so disallow it */
1779 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1782 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rrlmethod->set_first_handshake != NULL)
1783 s->rrlmethod->set_first_handshake(s->rrl, 1);
1785 if (s->max_pipelines != 0 && s->rrlmethod->set_max_pipelines != NULL)
1786 s->rrlmethod->set_max_pipelines(s->rrl, s->max_pipelines);
1791 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1792 int direction, int level,
1793 unsigned char *key, size_t keylen,
1794 unsigned char *iv, size_t ivlen,
1795 unsigned char *mackey, size_t mackeylen,
1796 const EVP_CIPHER *ciph, size_t taglen,
1797 int mactype, const EVP_MD *md,
1798 const SSL_COMP *comp)
1800 OSSL_PARAM options[4], *opts = options;
1801 OSSL_PARAM settings[6], *set = settings;
1802 const OSSL_RECORD_METHOD *origmeth = s->rrlmethod;
1803 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1804 const OSSL_RECORD_METHOD *meth;
1805 int use_etm, stream_mac = 0, tlstree = 0;
1806 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1807 int use_early_data = 0;
1808 uint32_t max_early_data;
1810 meth = ssl_select_next_record_layer(s, level);
1812 if (s->rrlmethod != NULL && !s->rrlmethod->free(s->rrl)) {
1813 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1818 s->rrlmethod = meth;
1820 if (!ossl_assert(s->rrlmethod != NULL)) {
1821 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1825 /* Parameters that *may* be supported by a record layer if passed */
1826 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1828 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1830 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1831 &s->rlayer.read_ahead);
1832 *opts = OSSL_PARAM_construct_end();
1834 /* Parameters that *must* be supported by a record layer if passed */
1835 if (direction == OSSL_RECORD_DIRECTION_READ) {
1836 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1837 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1840 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1843 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1844 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1847 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1852 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1856 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1860 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1863 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1864 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1866 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1867 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1871 * The record layer must check the amount of early data sent or received
1872 * using the early keys. A server also needs to worry about rejected early
1873 * data that might arrive when the handshake keys are in force.
1875 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1876 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1877 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1878 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1879 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1880 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1882 if (use_early_data) {
1883 max_early_data = ossl_get_max_early_data(s);
1885 if (max_early_data != 0)
1886 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1890 *set = OSSL_PARAM_construct_end();
1894 BIO *prev = s->rrlnext;
1895 unsigned int epoch = 0;;
1897 if (SSL_CONNECTION_IS_DTLS(s)
1898 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1899 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1901 s->rrlnext = BIO_new(BIO_s_mem());
1903 if (s->rrlnext == NULL) {
1905 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1909 rlret = s->rrlmethod->new_record_layer(sctx->libctx, sctx->propq,
1910 version, s->server, direction,
1911 level, epoch, key, keylen, iv,
1912 ivlen, mackey, mackeylen, ciph,
1913 taglen, mactype, md, comp, prev,
1914 s->rbio, s->rrlnext, NULL, NULL,
1916 rlayer_dispatch, s, &s->rrl);
1919 case OSSL_RECORD_RETURN_FATAL:
1920 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1923 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1924 if (s->rrlmethod != origmeth && origmeth != NULL) {
1926 * We tried a new record layer method, but it didn't work out,
1927 * so we fallback to the original method and try again
1929 s->rrlmethod = origmeth;
1932 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1935 case OSSL_RECORD_RETURN_SUCCESS:
1939 /* Should not happen */
1940 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1946 return ssl_post_record_layer_select(s);