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 (rl->numwpipes > 0)
72 ssl3_release_write_buffer(rl->s);
73 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
76 /* Checks if we have unprocessed read ahead data pending */
77 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
79 return rl->s->rrlmethod->unprocessed_read_pending(rl->s->rrl);
82 /* Checks if we have decrypted unread record data pending */
83 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
85 return (rl->curr_rec < rl->num_recs)
86 || rl->s->rrlmethod->processed_read_pending(rl->s->rrl);
89 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
91 return (rl->numwpipes > 0)
92 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
95 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
97 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
100 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
102 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
105 size_t ssl3_pending(const SSL *s)
108 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
113 if (SSL_CONNECTION_IS_DTLS(sc)) {
117 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
118 while ((item = pqueue_next(&iter)) != NULL) {
120 num += rdata->length;
124 for (i = 0; i < sc->rlayer.num_recs; i++) {
125 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
127 num += sc->rlayer.tlsrecs[i].length;
130 num += sc->rrlmethod->app_data_pending(sc->rrl);
135 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
137 ctx->default_read_buf_len = len;
140 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
142 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
146 sc->default_read_buf_len = len;
149 const char *SSL_rstate_string_long(const SSL *s)
151 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
156 switch (sc->rlayer.rstate) {
157 case SSL_ST_READ_HEADER:
158 return "read header";
159 case SSL_ST_READ_BODY:
161 case SSL_ST_READ_DONE:
168 const char *SSL_rstate_string(const SSL *s)
170 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
175 switch (sc->rlayer.rstate) {
176 case SSL_ST_READ_HEADER:
178 case SSL_ST_READ_BODY:
180 case SSL_ST_READ_DONE:
189 * Call this to write data in records of type 'type' It will return <= 0 if
190 * not all data has been sent or non-blocking IO.
192 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
195 const unsigned char *buf = buf_;
197 size_t n, max_send_fragment, split_send_fragment, maxpipes;
198 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
204 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
209 wb = &s->rlayer.wbuf[0];
210 s->rwstate = SSL_NOTHING;
211 tot = s->rlayer.wnum;
213 * ensure that if we end up with a smaller value of data to write out
214 * than the original len from a write which didn't complete for
215 * non-blocking I/O and also somehow ended up avoiding the check for
216 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
217 * possible to end up with (len-tot) as a large number that will then
218 * promptly send beyond the end of the users buffer ... so we trap and
219 * report the error in a way the user will notice
221 if ((len < s->rlayer.wnum)
222 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
223 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
227 if (s->early_data_state == SSL_EARLY_DATA_WRITING
228 && !ossl_early_data_count_ok(s, len, 0, 1)) {
229 /* SSLfatal() already called */
236 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
237 * into init unless we have writes pending - in which case we should finish
240 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
241 || s->ext.extra_tickets_expected > 0))
242 ossl_statem_set_in_init(s, 1);
245 * When writing early data on the server side we could be "in_init" in
246 * between receiving the EoED and the CF - but we don't want to handle those
249 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
250 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
251 i = s->handshake_func(ssl);
252 /* SSLfatal() already called */
261 * first check if there is a SSL3_BUFFER still being written out. This
262 * will happen with non blocking IO
265 /* SSLfatal() already called if appropriate */
266 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
269 /* XXX should we ssl3_release_write_buffer if i<0? */
270 s->rlayer.wnum = tot;
273 tot += tmpwrit; /* this might be last fragment */
275 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
277 * Depending on platform multi-block can deliver several *times*
278 * better performance. Downside is that it has to allocate
279 * jumbo buffer to accommodate up to 8 records, but the
280 * compromise is considered worthy.
282 if (type == SSL3_RT_APPLICATION_DATA
283 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
284 && s->compress == NULL
285 && s->msg_callback == NULL
287 && SSL_USE_EXPLICIT_IV(s)
288 && !BIO_get_ktls_send(s->wbio)
289 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
290 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
291 unsigned char aad[13];
292 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
296 /* minimize address aliasing conflicts */
297 if ((max_send_fragment & 0xfff) == 0)
298 max_send_fragment -= 512;
300 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
301 ssl3_release_write_buffer(s);
303 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
304 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
305 (int)max_send_fragment, NULL);
307 if (len >= 8 * max_send_fragment)
312 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
313 /* SSLfatal() already called */
316 } else if (tot == len) { /* done? */
317 /* free jumbo buffer */
318 ssl3_release_write_buffer(s);
325 if (n < 4 * max_send_fragment) {
326 /* free jumbo buffer */
327 ssl3_release_write_buffer(s);
331 if (s->s3.alert_dispatch) {
332 i = ssl->method->ssl_dispatch_alert(ssl);
334 /* SSLfatal() already called if appropriate */
335 s->rlayer.wnum = tot;
340 if (n >= 8 * max_send_fragment)
341 nw = max_send_fragment * (mb_param.interleave = 8);
343 nw = max_send_fragment * (mb_param.interleave = 4);
345 memcpy(aad, s->rlayer.write_sequence, 8);
347 aad[9] = (unsigned char)(s->version >> 8);
348 aad[10] = (unsigned char)(s->version);
355 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
356 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
357 sizeof(mb_param), &mb_param);
358 packlen = (size_t)packleni;
359 if (packleni <= 0 || packlen > wb->len) { /* never happens */
360 /* free jumbo buffer */
361 ssl3_release_write_buffer(s);
365 mb_param.out = wb->buf;
366 mb_param.inp = &buf[tot];
369 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
370 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
371 sizeof(mb_param), &mb_param) <= 0)
374 s->rlayer.write_sequence[7] += mb_param.interleave;
375 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
377 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
383 s->rlayer.wpend_tot = nw;
384 s->rlayer.wpend_buf = &buf[tot];
385 s->rlayer.wpend_type = type;
386 s->rlayer.wpend_ret = nw;
388 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
390 /* SSLfatal() already called if appropriate */
391 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
392 /* free jumbo buffer */
393 ssl3_release_write_buffer(s);
395 s->rlayer.wnum = tot;
399 /* free jumbo buffer */
400 ssl3_release_write_buffer(s);
401 *written = tot + tmpwrit;
408 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
409 if (tot == len) { /* done? */
410 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
411 ssl3_release_write_buffer(s);
419 max_send_fragment = ssl_get_max_send_fragment(s);
420 split_send_fragment = ssl_get_split_send_fragment(s);
422 * If max_pipelines is 0 then this means "undefined" and we default to
423 * 1 pipeline. Similarly if the cipher does not support pipelined
424 * processing then we also only use 1 pipeline, or if we're not using
427 maxpipes = s->max_pipelines;
428 if (maxpipes > SSL_MAX_PIPELINES) {
430 * We should have prevented this when we set max_pipelines so we
433 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
437 || s->enc_write_ctx == NULL
438 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
439 & EVP_CIPH_FLAG_PIPELINE) == 0
440 || !SSL_USE_EXPLICIT_IV(s))
442 if (max_send_fragment == 0
443 || split_send_fragment == 0
444 || split_send_fragment > max_send_fragment) {
446 * We should have prevented this when we set/get the split and max send
447 * fragments so we shouldn't get here
449 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
454 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
460 numpipes = ((n - 1) / split_send_fragment) + 1;
461 if (numpipes > maxpipes)
464 if (n / numpipes >= max_send_fragment) {
466 * We have enough data to completely fill all available
469 for (j = 0; j < numpipes; j++) {
470 pipelens[j] = max_send_fragment;
473 /* We can partially fill all available pipelines */
474 tmppipelen = n / numpipes;
475 remain = n % numpipes;
476 for (j = 0; j < numpipes; j++) {
477 pipelens[j] = tmppipelen;
483 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
486 /* SSLfatal() already called if appropriate */
487 /* XXX should we ssl3_release_write_buffer if i<0? */
488 s->rlayer.wnum = tot;
493 (type == SSL3_RT_APPLICATION_DATA &&
494 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
496 * next chunk of data should get another prepended empty fragment
497 * in ciphersuites with known-IV weakness:
499 s->s3.empty_fragment_done = 0;
502 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
503 && !SSL_CONNECTION_IS_DTLS(s))
504 ssl3_release_write_buffer(s);
506 *written = tot + tmpwrit;
515 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
516 size_t *pipelens, size_t numpipes,
517 int create_empty_fragment, size_t *written)
519 WPACKET pkt[SSL_MAX_PIPELINES];
520 SSL3_RECORD wr[SSL_MAX_PIPELINES];
523 unsigned char *recordstart;
524 int i, mac_size, clear = 0;
525 size_t prefix_len = 0;
530 size_t totlen = 0, len, wpinited = 0;
533 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
535 for (j = 0; j < numpipes; j++)
536 totlen += pipelens[j];
538 * first check if there is a SSL3_BUFFER still being written out. This
539 * will happen with non blocking IO
541 if (RECORD_LAYER_write_pending(&s->rlayer)) {
542 /* Calls SSLfatal() as required */
543 return ssl3_write_pending(s, type, buf, totlen, written);
546 /* If we have an alert to send, lets send it */
547 if (s->s3.alert_dispatch) {
548 i = ssl->method->ssl_dispatch_alert(ssl);
550 /* SSLfatal() already called if appropriate */
553 /* if it went, fall through and send more stuff */
556 if (s->rlayer.numwpipes < numpipes) {
557 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
558 /* SSLfatal() already called */
563 if (totlen == 0 && !create_empty_fragment)
569 || (s->enc_write_ctx == NULL)
570 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
571 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
574 mac_size = EVP_MD_CTX_get_size(s->write_hash);
576 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
582 * 'create_empty_fragment' is true only when this function calls itself
584 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
586 * countermeasure against known-IV weakness in CBC ciphersuites (see
587 * http://www.openssl.org/~bodo/tls-cbc.txt)
590 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
592 * recursive function call with 'create_empty_fragment' set; this
593 * prepares and buffers the data for an empty fragment (these
594 * 'prefix_len' bytes are sent out later together with the actual
597 size_t tmppipelen = 0;
600 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
602 /* SSLfatal() already called if appropriate */
607 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
608 /* insufficient space */
609 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
614 s->s3.empty_fragment_done = 1;
617 using_ktls = BIO_get_ktls_send(s->wbio);
620 * ktls doesn't modify the buffer, but to avoid a warning we need to
621 * discard the const qualifier.
622 * This doesn't leak memory because the buffers have been released when
625 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
626 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
627 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
628 goto wpacket_init_complete;
631 if (create_empty_fragment) {
632 wb = &s->rlayer.wbuf[0];
633 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
635 * extra fragment would be couple of cipher blocks, which would be
636 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
637 * payload, then we can just pretend we simply have two headers.
639 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
640 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
642 SSL3_BUFFER_set_offset(wb, align);
643 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
644 SSL3_BUFFER_get_len(wb), 0)
645 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
646 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
650 } else if (prefix_len) {
651 wb = &s->rlayer.wbuf[0];
652 if (!WPACKET_init_static_len(&pkt[0],
653 SSL3_BUFFER_get_buf(wb),
654 SSL3_BUFFER_get_len(wb), 0)
655 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
656 + prefix_len, NULL)) {
657 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
662 for (j = 0; j < numpipes; j++) {
665 wb = &s->rlayer.wbuf[j];
666 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
667 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
668 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
670 SSL3_BUFFER_set_offset(wb, align);
671 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
672 SSL3_BUFFER_get_len(wb), 0)
673 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
674 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
681 /* Explicit IV length, block ciphers appropriate version flag */
682 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
683 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
684 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
685 if (mode == EVP_CIPH_CBC_MODE) {
686 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
688 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
693 } else if (mode == EVP_CIPH_GCM_MODE) {
694 /* Need explicit part of IV for GCM mode */
695 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
696 } else if (mode == EVP_CIPH_CCM_MODE) {
697 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
701 wpacket_init_complete:
704 /* Clear our SSL3_RECORD structures */
705 memset(wr, 0, sizeof(wr));
706 for (j = 0; j < numpipes; j++) {
707 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
709 unsigned char *compressdata = NULL;
711 unsigned int rectype;
717 * In TLSv1.3, once encrypting, we always use application data for the
720 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
721 && s->enc_write_ctx != NULL
722 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
723 || type != SSL3_RT_ALERT))
724 rectype = SSL3_RT_APPLICATION_DATA;
727 SSL3_RECORD_set_type(thiswr, rectype);
730 * Some servers hang if initial client hello is larger than 256 bytes
731 * and record version number > TLS 1.0
733 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
735 && TLS1_get_version(ssl) > TLS1_VERSION
736 && s->hello_retry_request == SSL_HRR_NONE)
737 version = TLS1_VERSION;
738 SSL3_RECORD_set_rec_version(thiswr, version);
740 maxcomplen = pipelens[j];
741 if (s->compress != NULL)
742 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
745 * When using offload kernel will write the header.
746 * Otherwise write the header now
749 && (!WPACKET_put_bytes_u8(thispkt, rectype)
750 || !WPACKET_put_bytes_u16(thispkt, version)
751 || !WPACKET_start_sub_packet_u16(thispkt)
753 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
755 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
757 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
761 /* lets setup the record stuff. */
762 SSL3_RECORD_set_data(thiswr, compressdata);
763 SSL3_RECORD_set_length(thiswr, pipelens[j]);
764 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
765 totlen += pipelens[j];
768 * we now 'read' from thiswr->input, thiswr->length bytes into
772 /* first we compress */
773 if (s->compress != NULL) {
774 if (!ssl3_do_compress(s, thiswr)
775 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
776 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
781 SSL3_RECORD_reset_data(&wr[j]);
783 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
784 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
787 SSL3_RECORD_reset_input(&wr[j]);
791 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
793 && s->enc_write_ctx != NULL
794 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
795 || type != SSL3_RT_ALERT)) {
796 size_t rlen, max_send_fragment;
798 if (!WPACKET_put_bytes_u8(thispkt, type)) {
799 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
802 SSL3_RECORD_add_length(thiswr, 1);
804 /* Add TLS1.3 padding */
805 max_send_fragment = ssl_get_max_send_fragment(s);
806 rlen = SSL3_RECORD_get_length(thiswr);
807 if (rlen < max_send_fragment) {
809 size_t max_padding = max_send_fragment - rlen;
810 if (s->record_padding_cb != NULL) {
811 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
812 } else if (s->block_padding > 0) {
813 size_t mask = s->block_padding - 1;
816 /* optimize for power of 2 */
817 if ((s->block_padding & mask) == 0)
818 remainder = rlen & mask;
820 remainder = rlen % s->block_padding;
821 /* don't want to add a block of padding if we don't have to */
825 padding = s->block_padding - remainder;
828 /* do not allow the record to exceed max plaintext length */
829 if (padding > max_padding)
830 padding = max_padding;
831 if (!WPACKET_memset(thispkt, 0, padding)) {
832 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
833 ERR_R_INTERNAL_ERROR);
836 SSL3_RECORD_add_length(thiswr, padding);
842 * we should still have the output to thiswr->data and the input from
843 * wr->input. Length should be thiswr->length. thiswr->data still points
847 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
850 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
851 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
852 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
858 * Reserve some bytes for any growth that may occur during encryption.
859 * This will be at most one cipher block or the tag length if using
860 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
863 if (!WPACKET_reserve_bytes(thispkt,
864 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
867 * We also need next the amount of bytes written to this
870 || !WPACKET_get_length(thispkt, &len)) {
871 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
875 /* Get a pointer to the start of this record excluding header */
876 recordstart = WPACKET_get_curr(thispkt) - len;
877 SSL3_RECORD_set_data(thiswr, recordstart);
878 SSL3_RECORD_reset_input(thiswr);
879 SSL3_RECORD_set_length(thiswr, len);
883 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
885 * We haven't actually negotiated the version yet, but we're trying to
886 * send early data - so we need to use the tls13enc function.
888 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
889 if (!ossl_statem_in_error(s)) {
890 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
896 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
898 if (!ossl_statem_in_error(s)) {
899 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
906 for (j = 0; j < numpipes; j++) {
915 /* Allocate bytes for the encryption overhead */
916 if (!WPACKET_get_length(thispkt, &origlen)
917 /* Encryption should never shrink the data! */
918 || origlen > thiswr->length
919 || (thiswr->length > origlen
920 && !WPACKET_allocate_bytes(thispkt,
921 thiswr->length - origlen,
923 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
926 if (SSL_WRITE_ETM(s) && mac_size != 0) {
929 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
930 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
931 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
934 SSL3_RECORD_add_length(thiswr, mac_size);
937 if (!WPACKET_get_length(thispkt, &len)
938 || !WPACKET_close(thispkt)) {
939 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
943 if (s->msg_callback) {
944 recordstart = WPACKET_get_curr(thispkt) - len
945 - SSL3_RT_HEADER_LENGTH;
946 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
947 SSL3_RT_HEADER_LENGTH, ssl,
948 s->msg_callback_arg);
950 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
951 unsigned char ctype = type;
953 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
954 &ctype, 1, ssl, s->msg_callback_arg);
958 if (!WPACKET_finish(thispkt)) {
959 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
963 /* header is added by the kernel when using offload */
964 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
966 if (create_empty_fragment) {
968 * we are in a recursive call; just return the length, don't write
972 /* We should never be pipelining an empty fragment!! */
973 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
976 *written = SSL3_RECORD_get_length(thiswr);
982 * we should now have thiswr->data pointing to the encrypted data, which
983 * is thiswr->length long
985 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
988 /* now let's set up wb */
989 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
990 prefix_len + SSL3_RECORD_get_length(thiswr));
994 * memorize arguments so that ssl3_write_pending can detect bad write
997 s->rlayer.wpend_tot = totlen;
998 s->rlayer.wpend_buf = buf;
999 s->rlayer.wpend_type = type;
1000 s->rlayer.wpend_ret = totlen;
1002 /* we now just need to write the buffer */
1003 return ssl3_write_pending(s, type, buf, totlen, written);
1005 for (j = 0; j < wpinited; j++)
1006 WPACKET_cleanup(&pkt[j]);
1010 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1012 * Return values are as per SSL_write()
1014 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1015 size_t len, size_t *written)
1018 SSL3_BUFFER *wb = s->rlayer.wbuf;
1022 if ((s->rlayer.wpend_tot > len)
1023 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1024 && (s->rlayer.wpend_buf != buf))
1025 || (s->rlayer.wpend_type != type)) {
1026 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1031 /* Loop until we find a buffer we haven't written out yet */
1032 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1033 && currbuf < s->rlayer.numwpipes - 1) {
1038 if (s->wbio != NULL) {
1039 s->rwstate = SSL_WRITING;
1042 * To prevent coalescing of control and data messages,
1043 * such as in buffer_write, we flush the BIO
1045 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1046 i = BIO_flush(s->wbio);
1049 BIO_set_ktls_ctrl_msg(s->wbio, type);
1051 i = BIO_write(s->wbio, (char *)
1052 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1053 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1054 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1058 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1063 * When an empty fragment is sent on a connection using KTLS,
1064 * it is sent as a write of zero bytes. If this zero byte
1065 * write succeeds, i will be 0 rather than a non-zero value.
1066 * Treat i == 0 as success rather than an error for zero byte
1067 * writes to permit this case.
1069 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1070 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1071 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1072 if (currbuf + 1 < s->rlayer.numwpipes)
1074 s->rwstate = SSL_NOTHING;
1075 *written = s->rlayer.wpend_ret;
1077 } else if (i <= 0) {
1078 if (SSL_CONNECTION_IS_DTLS(s)) {
1080 * For DTLS, just drop it. That's kind of the whole point in
1081 * using a datagram service
1083 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1087 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1088 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1092 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1095 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1097 if (ret == OSSL_RECORD_RETURN_RETRY) {
1098 s->rwstate = SSL_READING;
1101 s->rwstate = SSL_NOTHING;
1102 if (ret == OSSL_RECORD_RETURN_EOF) {
1103 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1104 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1105 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1108 ERR_set_debug(file, line, 0);
1109 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1110 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1112 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1114 ERR_set_debug(file, line, 0);
1115 ossl_statem_fatal(s, s->rrlmethod->get_alert_code(s->rrl),
1116 SSL_R_RECORD_LAYER_FAILURE, NULL);
1119 * The record layer distinguishes the cases of EOF, non-fatal
1120 * err and retry. Upper layers do not.
1121 * If we got a retry or success then *ret is already correct,
1122 * otherwise we need to convert the return value.
1124 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1126 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1133 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
1135 if (rr->rechandle != NULL) {
1136 /* The record layer allocated the buffers for this record */
1137 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1139 /* We allocated the buffers for this record (only happens with DTLS) */
1140 OPENSSL_free(rr->data);
1142 s->rlayer.curr_rec++;
1146 * Return up to 'len' payload bytes received in 'type' records.
1147 * 'type' is one of the following:
1149 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1150 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1151 * - 0 (during a shutdown, no data has to be returned)
1153 * If we don't have stored data to work from, read a SSL/TLS record first
1154 * (possibly multiple records if we still don't have anything to return).
1156 * This function must handle any surprises the peer may have for us, such as
1157 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1158 * messages are treated as if they were handshake messages *if* the |recvd_type|
1159 * argument is non NULL.
1160 * Also if record payloads contain fragments too small to process, we store
1161 * them until there is enough for the respective protocol (the record protocol
1162 * may use arbitrary fragmentation and even interleaving):
1163 * Change cipher spec protocol
1164 * just 1 byte needed, no need for keeping anything stored
1166 * 2 bytes needed (AlertLevel, AlertDescription)
1167 * Handshake protocol
1168 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1169 * to detect unexpected Client Hello and Hello Request messages
1170 * here, anything else is handled by higher layers
1171 * Application data protocol
1172 * none of our business
1174 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1175 size_t len, int peek, size_t *readbytes)
1178 size_t n, curr_rec, totalbytes;
1180 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1182 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1184 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1187 && (type != SSL3_RT_APPLICATION_DATA)
1188 && (type != SSL3_RT_HANDSHAKE))
1189 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1190 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1194 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1195 /* (partially) satisfy request from storage */
1197 unsigned char *src = s->rlayer.handshake_fragment;
1198 unsigned char *dst = buf;
1203 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1206 s->rlayer.handshake_fragment_len--;
1209 /* move any remaining fragment bytes: */
1210 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1211 s->rlayer.handshake_fragment[k] = *src++;
1213 if (recvd_type != NULL)
1214 *recvd_type = SSL3_RT_HANDSHAKE;
1221 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1224 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1225 /* type == SSL3_RT_APPLICATION_DATA */
1226 i = s->handshake_func(ssl);
1227 /* SSLfatal() already called */
1234 s->rwstate = SSL_NOTHING;
1237 * For each record 'i' up to |num_recs]
1238 * rr[i].type - is the type of record
1239 * rr[i].data, - data
1240 * rr[i].off, - offset into 'data' for next read
1241 * rr[i].length, - number of bytes.
1243 /* get new records if necessary */
1244 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1245 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1247 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1249 ret = HANDLE_RLAYER_RETURN(s,
1250 s->rrlmethod->read_record(s->rrl, &rr->rechandle,
1251 &rr->version, &rr->type,
1252 &rr->data, &rr->length,
1255 /* SSLfatal() already called if appropriate */
1259 s->rlayer.num_recs++;
1260 } while (s->rrlmethod->processed_read_pending(s->rrl)
1261 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1263 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1265 if (s->rlayer.handshake_fragment_len > 0
1266 && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1267 && SSL_CONNECTION_IS_TLS13(s)) {
1268 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1269 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1274 * Reset the count of consecutive warning alerts if we've got a non-empty
1275 * record that isn't an alert.
1277 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1278 s->rlayer.alert_count = 0;
1280 /* we now have a packet which can be read and processed */
1282 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1283 * reset by ssl3_get_finished */
1284 && (rr->type != SSL3_RT_HANDSHAKE)) {
1285 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1286 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1291 * If the other end has shut down, throw anything we read away (even in
1294 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1295 s->rlayer.curr_rec++;
1296 s->rwstate = SSL_NOTHING;
1300 if (type == rr->type
1301 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1302 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1305 * SSL3_RT_APPLICATION_DATA or
1306 * SSL3_RT_HANDSHAKE or
1307 * SSL3_RT_CHANGE_CIPHER_SPEC
1310 * make sure that we are not getting application data when we are
1311 * doing a handshake for the first time
1313 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1314 && s->enc_read_ctx == NULL) {
1315 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1319 if (type == SSL3_RT_HANDSHAKE
1320 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1321 && s->rlayer.handshake_fragment_len > 0) {
1322 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1326 if (recvd_type != NULL)
1327 *recvd_type = rr->type;
1331 * Skip a zero length record. This ensures multiple calls to
1332 * SSL_read() with a zero length buffer will eventually cause
1333 * SSL_pending() to report data as being available.
1335 if (rr->length == 0)
1336 ssl_release_record(s, rr);
1342 curr_rec = s->rlayer.curr_rec;
1344 if (len - totalbytes > rr->length)
1347 n = len - totalbytes;
1349 memcpy(buf, &(rr->data[rr->off]), n);
1352 /* Mark any zero length record as consumed CVE-2016-6305 */
1353 if (rr->length == 0)
1354 ssl_release_record(s, rr);
1356 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1357 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1360 if (rr->length == 0) {
1361 /* TODO(RECLAYER): What to do with this? Is it needed? */
1363 s->rlayer.rstate = SSL_ST_READ_HEADER;
1365 ssl_release_record(s, rr);
1369 || (peek && n == rr->length)) {
1374 } while (type == SSL3_RT_APPLICATION_DATA
1375 && curr_rec < s->rlayer.num_recs
1376 && totalbytes < len);
1377 if (totalbytes == 0) {
1378 /* We must have read empty records. Get more data */
1381 /* TODO(RECLAYER): FIX ME */
1383 if (!peek && curr_rec == s->rlayer.num_recs
1384 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1385 && SSL3_BUFFER_get_left(rbuf) == 0)
1386 ssl3_release_read_buffer(s);
1388 *readbytes = totalbytes;
1393 * If we get here, then type != rr->type; if we have a handshake message,
1394 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1395 * were actually expecting a CCS).
1399 * Lets just double check that we've not got an SSLv2 record
1401 if (rr->version == SSL2_VERSION) {
1403 * Should never happen. ssl3_get_record() should only give us an SSLv2
1404 * record back if this is the first packet and we are looking for an
1405 * initial ClientHello. Therefore |type| should always be equal to
1406 * |rr->type|. If not then something has gone horribly wrong
1408 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1412 if (ssl->method->version == TLS_ANY_VERSION
1413 && (s->server || rr->type != SSL3_RT_ALERT)) {
1415 * If we've got this far and still haven't decided on what version
1416 * we're using then this must be a client side alert we're dealing
1417 * with. We shouldn't be receiving anything other than a ClientHello
1418 * if we are a server.
1420 s->version = rr->version;
1421 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1426 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1427 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1430 if (rr->type == SSL3_RT_ALERT) {
1431 unsigned int alert_level, alert_descr;
1432 unsigned char *alert_bytes = rr->data
1436 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1437 || !PACKET_get_1(&alert, &alert_level)
1438 || !PACKET_get_1(&alert, &alert_descr)
1439 || PACKET_remaining(&alert) != 0) {
1440 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1444 if (s->msg_callback)
1445 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1446 s->msg_callback_arg);
1448 if (s->info_callback != NULL)
1449 cb = s->info_callback;
1450 else if (ssl->ctx->info_callback != NULL)
1451 cb = ssl->ctx->info_callback;
1454 j = (alert_level << 8) | alert_descr;
1455 cb(ssl, SSL_CB_READ_ALERT, j);
1458 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1459 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1460 s->s3.warn_alert = alert_descr;
1461 ssl_release_record(s, rr);
1463 s->rlayer.alert_count++;
1464 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1465 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1466 SSL_R_TOO_MANY_WARN_ALERTS);
1472 * Apart from close_notify the only other warning alert in TLSv1.3
1473 * is user_cancelled - which we just ignore.
1475 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1477 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1478 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1479 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1481 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1482 s->rwstate = SSL_NOTHING;
1483 s->s3.fatal_alert = alert_descr;
1484 SSLfatal_data(s, SSL_AD_NO_ALERT,
1485 SSL_AD_REASON_OFFSET + alert_descr,
1486 "SSL alert number %d", alert_descr);
1487 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1488 ssl_release_record(s, rr);
1489 SSL_CTX_remove_session(s->session_ctx, s->session);
1491 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1493 * This is a warning but we receive it if we requested
1494 * renegotiation and the peer denied it. Terminate with a fatal
1495 * alert because if application tried to renegotiate it
1496 * presumably had a good reason and expects it to succeed. In
1497 * future we might have a renegotiation where we don't care if
1498 * the peer refused it where we carry on.
1500 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1502 } else if (alert_level == SSL3_AL_WARNING) {
1503 /* We ignore any other warning alert in TLSv1.2 and below */
1507 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1511 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1512 if (rr->type == SSL3_RT_HANDSHAKE) {
1516 * We ignore any handshake messages sent to us unless they are
1517 * TLSv1.3 in which case we want to process them. For all other
1518 * handshake messages we can't do anything reasonable with them
1519 * because we are unable to write any response due to having already
1520 * sent close_notify.
1522 if (!SSL_CONNECTION_IS_TLS13(s)) {
1523 ssl_release_record(s, rr);
1525 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1528 s->rwstate = SSL_READING;
1529 rbio = SSL_get_rbio(ssl);
1530 BIO_clear_retry_flags(rbio);
1531 BIO_set_retry_read(rbio);
1536 * The peer is continuing to send application data, but we have
1537 * already sent close_notify. If this was expected we should have
1538 * been called via SSL_read() and this would have been handled
1540 * No alert sent because we already sent close_notify
1542 ssl_release_record(s, rr);
1543 SSLfatal(s, SSL_AD_NO_ALERT,
1544 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1550 * For handshake data we have 'fragment' storage, so fill that so that we
1551 * can process the header at a fixed place. This is done after the
1552 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1553 * that we're just going to discard.
1555 if (rr->type == SSL3_RT_HANDSHAKE) {
1556 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1557 unsigned char *dest = s->rlayer.handshake_fragment;
1558 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1560 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1562 n = rr->length; /* available bytes */
1564 /* now move 'n' bytes: */
1565 memcpy(dest + *dest_len, rr->data + rr->off, n);
1569 if (rr->length == 0)
1570 ssl_release_record(s, rr);
1572 if (*dest_len < dest_maxlen)
1573 goto start; /* fragment was too small */
1576 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1577 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1582 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1583 * protocol violation)
1585 if ((s->rlayer.handshake_fragment_len >= 4)
1586 && !ossl_statem_get_in_handshake(s)) {
1587 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1589 /* We found handshake data, so we're going back into init */
1590 ossl_statem_set_in_init(s, 1);
1592 i = s->handshake_func(ssl);
1593 /* SSLfatal() already called if appropriate */
1601 * If we were actually trying to read early data and we found a
1602 * handshake message, then we don't want to continue to try and read
1603 * the application data any more. It won't be "early" now.
1608 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1609 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1612 * In the case where we try to read application data, but we
1613 * trigger an SSL handshake, we return -1 with the retry
1614 * option set. Otherwise renegotiation may cause nasty
1615 * problems in the blocking world
1617 s->rwstate = SSL_READING;
1618 bio = SSL_get_rbio(ssl);
1619 BIO_clear_retry_flags(bio);
1620 BIO_set_retry_read(bio);
1630 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1631 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1632 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1633 * no progress is being made and the peer continually sends unrecognised
1634 * record types, using up resources processing them.
1636 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1638 case SSL3_RT_CHANGE_CIPHER_SPEC:
1640 case SSL3_RT_HANDSHAKE:
1642 * we already handled all of these, with the possible exception of
1643 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1644 * that should not happen when type != rr->type
1646 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1648 case SSL3_RT_APPLICATION_DATA:
1650 * At this point, we were expecting handshake data, but have
1651 * application data. If the library was running inside ssl3_read()
1652 * (i.e. in_read_app_data is set) and it makes sense to read
1653 * application data at this point (session renegotiation not yet
1654 * started), we will indulge it.
1656 if (ossl_statem_app_data_allowed(s)) {
1657 s->s3.in_read_app_data = 2;
1659 } else if (ossl_statem_skip_early_data(s)) {
1661 * This can happen after a client sends a CH followed by early_data,
1662 * but the server responds with a HelloRetryRequest. The server
1663 * reads the next record from the client expecting to find a
1664 * plaintext ClientHello but gets a record which appears to be
1665 * application data. The trial decrypt "works" because null
1666 * decryption was applied. We just skip it and move on to the next
1669 if (!ossl_early_data_count_ok(s, rr->length,
1670 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1671 /* SSLfatal() already called */
1674 ssl_release_record(s, rr);
1677 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1683 void ssl3_record_sequence_update(unsigned char *seq)
1687 for (i = 7; i >= 0; i--) {
1695 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1696 * format and false otherwise.
1698 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1700 if (SSL_CONNECTION_IS_DTLS(rl->s))
1702 return rl->tlsrecs[0].version == SSL2_VERSION;
1706 * Returns the length in bytes of the current rrec
1708 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1710 return SSL3_RECORD_get_length(&rl->rrec[0]);
1713 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1714 static void rlayer_msg_callback_wrapper(int write_p, int version,
1715 int content_type, const void *buf,
1716 size_t len, void *cbarg)
1718 SSL_CONNECTION *s = cbarg;
1719 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1721 if (s->msg_callback != NULL)
1722 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1723 s->msg_callback_arg);
1726 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1727 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1730 SSL_CONNECTION *s = cbarg;
1732 return ssl_security(s, op, bits, nid, other);
1735 static const OSSL_DISPATCH rlayer_dispatch[] = {
1736 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1737 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1738 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1742 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1746 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1747 if (SSL_CONNECTION_IS_DTLS(s))
1748 return &ossl_dtls_record_method;
1750 return &ossl_tls_record_method;
1753 #ifndef OPENSSL_NO_KTLS
1754 /* KTLS does not support renegotiation */
1755 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1756 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1757 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1758 return &ossl_ktls_record_method;
1761 /* Default to the current OSSL_RECORD_METHOD */
1762 return s->rrlmethod;
1765 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1767 #ifndef OPENSSL_NO_KTLS
1768 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1770 if (s->rrlmethod == &ossl_ktls_record_method) {
1771 /* KTLS does not support renegotiation so disallow it */
1772 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1775 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rrlmethod->set_first_handshake != NULL)
1776 s->rrlmethod->set_first_handshake(s->rrl, 1);
1778 if (s->max_pipelines != 0 && s->rrlmethod->set_max_pipelines != NULL)
1779 s->rrlmethod->set_max_pipelines(s->rrl, s->max_pipelines);
1784 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1785 int direction, int level,
1786 unsigned char *key, size_t keylen,
1787 unsigned char *iv, size_t ivlen,
1788 unsigned char *mackey, size_t mackeylen,
1789 const EVP_CIPHER *ciph, size_t taglen,
1790 int mactype, const EVP_MD *md,
1791 const SSL_COMP *comp)
1793 OSSL_PARAM options[5], *opts = options;
1794 OSSL_PARAM settings[6], *set = settings;
1795 const OSSL_RECORD_METHOD *origmeth = s->rrlmethod;
1796 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1797 const OSSL_RECORD_METHOD *meth;
1798 int use_etm, stream_mac = 0, tlstree = 0;
1799 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1800 int use_early_data = 0;
1801 uint32_t max_early_data;
1803 meth = ssl_select_next_record_layer(s, level);
1805 if (s->rrlmethod != NULL && !s->rrlmethod->free(s->rrl)) {
1806 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1811 s->rrlmethod = meth;
1813 if (!ossl_assert(s->rrlmethod != NULL)) {
1814 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1818 /* Parameters that *may* be supported by a record layer if passed */
1819 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1821 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1823 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1824 &s->default_read_buf_len);
1825 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1826 &s->rlayer.read_ahead);
1827 *opts = OSSL_PARAM_construct_end();
1829 /* Parameters that *must* be supported by a record layer if passed */
1830 if (direction == OSSL_RECORD_DIRECTION_READ) {
1831 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1832 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1835 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1838 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1839 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1842 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1847 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1851 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1855 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1858 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1859 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1861 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1862 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1866 * The record layer must check the amount of early data sent or received
1867 * using the early keys. A server also needs to worry about rejected early
1868 * data that might arrive when the handshake keys are in force.
1870 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1871 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1872 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1873 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1874 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1875 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1877 if (use_early_data) {
1878 max_early_data = ossl_get_max_early_data(s);
1880 if (max_early_data != 0)
1881 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1885 *set = OSSL_PARAM_construct_end();
1889 BIO *prev = s->rrlnext;
1890 unsigned int epoch = 0;;
1892 if (SSL_CONNECTION_IS_DTLS(s)
1893 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1894 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1896 s->rrlnext = BIO_new(BIO_s_mem());
1898 if (s->rrlnext == NULL) {
1900 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1904 rlret = s->rrlmethod->new_record_layer(sctx->libctx, sctx->propq,
1905 version, s->server, direction,
1906 level, epoch, key, keylen, iv,
1907 ivlen, mackey, mackeylen, ciph,
1908 taglen, mactype, md, comp, prev,
1909 s->rbio, s->rrlnext, NULL, NULL,
1911 rlayer_dispatch, s, &s->rrl);
1914 case OSSL_RECORD_RETURN_FATAL:
1915 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1918 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1919 if (s->rrlmethod != origmeth && origmeth != NULL) {
1921 * We tried a new record layer method, but it didn't work out,
1922 * so we fallback to the original method and try again
1924 s->rrlmethod = origmeth;
1927 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1930 case OSSL_RECORD_RETURN_SUCCESS:
1934 /* Should not happen */
1935 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1941 return ssl_post_record_layer_select(s);